【问题标题】:GSON : Parsing JSON key value with sometime Object & sometime ArrayGSON:使用有时对象和有时数组解析 JSON 键值
【发布时间】:2018-05-22 10:16:24
【问题描述】:

我正在使用 GSON 来解析 JSON 字符串,但有一个键包含 Json,它有时是对象,有时是数组。 所以请帮助我使用 gson 将其解析为模型类。

与数组共鸣

{
   "key" : "test",
   "value" : [
                {
                  "id" : 1,
                  "name": "abc"
                },
                {
                  "id" : 2,
                  "name": "xyz"
                }
             ]
}

与对象产生共鸣

{
   "key" : "test",
   "value" : {
                 "id" : 1,
                 "name": "abc"
             }
}

MyModel.java

public class MyModel implements Serializable {
@SerializedName("key")
@Expose
public String key;

@SerializedName("value")
@Expose
public ArrayList<ValueModel> value;

public class ValueModel implements Serializable {
    @SerializedName("id")
    @Expose
    public String id;

    @SerializedName("name")
    @Expose
    public String name;
   }
}

但由于数据类型数组和对象,它总是进入异常状态 我也尝试过使用 JsonDeserializer 但我认为我没有很好地实现它 所以请帮我解决它并解析json

【问题讨论】:

  • 简单的方法只是改变后端的响应要求您的后端开发人员每次都以相同的格式给出响应
  • 我正在使用第三方 API,它有这种类型的响应。我怎样才能告诉他为我改变回应?
  • 你知道在什么情况下object会出现而不是array,反之亦然吗?
  • 只有一个值的时候变成object else Array
  • 我也需要回答同样的问题。

标签: android gson


【解决方案1】:

简单的尝试以 Object 的形式访问,然后检查 instanceof Object 并根据它解析数据

String json="";

JSONObject jsonMain=new JSONObject(json);

Object objectType=jsonMain.get("value");
  if (objectType instanceof JSONObject) {
    JSONObject jsonObjectType=(JSONObject)objectType;
  } else if (json instanceof JSONArray) {
    JSONArray jsonArrayType=(JSONArray)objectType;
  }

如果您使用的是 JSONObject

  if (objectType  instanceof JSONObject) {
     UserDetails details = new Gson().fromJson(objectType, UserDetails.class);

 } else if (objectType  instanceof JSONArray) {
     Type listType = new TypeToken<List<UserDetails>>() {
     }.getType();
     List<UserDetails> list = new Gson().fromJson(objectType, listType);
     userDetailsList.addAll(list);
 }

【讨论】:

  • 我得到了你的答案,但根据它我确定它只是对象或数组,但如果我想将对象转换为数组。此功能由 GSON 提供。请看stackoverflow.com/questions/7668507/gson-handle-object-or-array
  • 我想自己处理成模型
  • @SandipPatel 我已经更新了答案,您不需要同时使用模型处理和手动解析,因为 JSONResponse 不固定
【解决方案2】:

为对象添加 SerializedName 名称并添加自定义 getter

public class MyModel implements Serializable {
      @SerializedName("key")
      @Expose
      public String key;

      @SerializedName("value")
      @Expose
      public ArrayList<ValueModel> valueList;

      @SerializedName("value")
      @Expose
      ValueModel modelValue;

      public List<ValueModel> getValueModel() {
          return Collections.singletonList(modelValue);
       }

public class ValueModel implements Serializable {
        @SerializedName("id")
        @Expose
        public String id;

        @SerializedName("name")
        @Expose
        public String name;
       }
     }

【讨论】:

  • 如果有对象,我想将对象转换为数组,如果是数组,则可以。
  • 这可以通过使用 JsonDeserializer 或 JsonAdapter 来完成,但我不知道如何实现它。如果你知道那么请帮助我实现它。谢谢。
  • 我更新我的答案请检查,你也可以使用public List&lt;ValueModel&gt; getValueModel () { return Arrays.asList(modelValue); }
  • 您为单个键“值”使用了两个不同的对象。但是 GSON 为此提供了 JsonAdapter 或 JsonDeserializer,但我不能很好地理解它。请参考此链接stackoverflow.com/questions/7668507/gson-handle-object-or-array
  • 谢谢你给我一个新的有价值的信息。您可以使用 JsonAdapter(如您发布的链接)来解决您的问题。
【解决方案3】:

你可以试试:

gson.fromJson(jsonString, classOfModel)

我认为你可以删除@SerializedName@Expose 标签。

【讨论】:

    【解决方案4】:

    万一您没有找到答案。 检查一下。

    public class SomeModel  {
    
        @SerializedName("my_model")
         private MyModel[] myModel;
    
        public List<MyModel> getMyModel() {
    
           return new LinkedList<MyModel>( Arrays.asList(myModel));
    
        }
    
         public static class MyModelDeserializer implements JsonDeserializer<MyModel[]> {
    
        @Override
         public MyModel[] deserialize(JsonElement json, Type typeOfT,
         JsonDeserializationContext context) throws JsonParseException {
    
          if (json instanceof JsonArray) {
    
                return new Gson().fromJson(json, MyModel[].class);
    
          }
    
          MyModel child = context.deserialize(json, MyModel.class);
    
             return new MyModel[] { child };
          }
      }
    }
    

    参考:https://nayaneshguptetechstuff.wordpress.com/2014/06/21/parsing-json-with-gson-sometimes-object-sometimes-array/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      相关资源
      最近更新 更多