hellzone
hellzone

Reputation: 5246

How to handle json object or array?

I have an errorLogList json data which can be object or array. I want to Gson to handle both array and objects. I have found some TypeAdapters but I don't know how to use it with inner String List. Is there any solution?

Gson gson = new Gson();
LogData logData= gson.fromJson(jsonData, LogData.class);

JSON data examples;

"{"time":1473092580000,"logs":{"errorLog":{"errorLogList":"fatal error occured","id":"2323232"}}}"

"{"time":1473092580000,"logs":{"errorLog":{"errorLogList":["fatal error occured","warning occured"],"id":"2323232"}}}"

public class LogData{
  private Log logs;
  ....
}

public class Log{
   private ErrorLog errorLog;
   ....
}

public class ErrorLog{
  private List<String> errorLogList;
}

Upvotes: 0

Views: 103

Answers (2)

Sachin Gupta
Sachin Gupta

Reputation: 8388

You can try this:

GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.registerTypeAdapter(ErrorLog.class, new JsonDeserializer<ErrorLog>() {
  @Override
  public ErrorLog deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {

    ErrorLog errorLog = new ErrorLog();
    List<String> errorLogList = new ArrayList<>();

    JsonElement errorLogJson = json.getAsJsonObject().get("errorLogList");

    if (errorLogJson.isJsonArray()) {
      JsonArray jsonArray = errorLogJson.getAsJsonArray();
      for (int i = 0; i < jsonArray.size(); i++) {
        errorLogList.add(jsonArray.get(i).getAsString());
      }
    } else{
      errorLogList.add(errorLogJson.getAsString());
    }

    errorLog.setErrorLogList(errorLogList);

    return errorLog;
  }
});

LogData logData = gsonBuilder.create().fromJson(jsonData, LogData.class);

Upvotes: 2

Bernard
Bernard

Reputation: 375

Gson offers the possibility to create custom Serializer(JsonSerializer<?>) and Deserializer(JsonDeserializer<?>). They can be registered like this:

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(LogData.class, new LogDataDeserializer());
    Gson gson = gsonBuilder.create();

You can deserialize your JSON like this:

    Type listOfIssuesType = new TypeToken<ArrayList<LogData>>() {
    }.getType();
    List<LogData> logData= getIssueGson().fromJson(json, listOfIssuesType);

For deserializing an array I use the following function:

public List<String> getArrayNullSave(JsonObject object, String fieldName) {
    if(object.get(fieldName) == null || object.get(fieldName).isJsonNull())
        return null;
    List<String> list = new ArrayList<String>();
    for (JsonElement jsonElement : object.get(fieldName).getAsJsonArray()) {
        list.add(jsonElement.getAsString());
    }
    return list;
}

Hope it helps.

Upvotes: 0

Related Questions