如何处理json对象或数组?

时间:2016-10-04 07:14:17

标签: java json gson

我有一个errorLogList json数据,可以是对象或数组。我想让Gson处理数组和对象。我找到了一些TypeAdapter但我不知道如何将它与内部String List一起使用。有没有解决方案?

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

JSON数据示例;

"{"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;
}

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

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);

答案 1 :(得分:0)

Gson提供了创建自定义序列化程序(JsonSerializer<?>)和反序列化程序(JsonDeserializer<?>)的可能性。他们可以这样注册:

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

您可以像这样反序列化您的JSON:

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

对于反序列化数组,我使用以下函数:

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;
}

希望它有所帮助。