【问题标题】:Deserialize strange json with retrofit and Gson使用改造和 Gson 反序列化奇怪的 json
【发布时间】:2016-05-10 20:59:34
【问题描述】:

我需要反序列化这个json:

    {    
    "17": {
       "entity_id": "17",
       "attribute_set_id": "4",
       "type_id": "virtual",
       },
    "18": {
       "entity_id": "18",
       "attribute_set_id": "9",
       "type_id": "virtual"
       }
    }

但使用改造和 Gson 似乎是不可能的。

OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new SigningInterceptor(consumer))
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl("http://endpoint/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

那么,我该如何反序列化这个生物呢?我可以使用什么类型的?

【问题讨论】:

  • 您可以使用 entity_id 和其他属性声明对象,然后您的服务器响应类将只有该对象

标签: android json gson retrofit2


【解决方案1】:

这是映射,其中"17" 是一个键,

{ "entity_id": "17", "attribute_set_id": "4", "type_id": "virtual", }

是一个对象。

试试 HashMap。

【讨论】:

    【解决方案2】:

    您可以创建一个 Java 类(例如 Item)来包含成员变量(entity_idattribute_set_idtype_id) - 我创建了 this Gist,并使用 JSONObject 来执行以下操作:

    JSONObject yourJSON = new JSONObject(jsonString);
    //This will iterate through 17, 18, etc
    Iterator<String> keysIterator = yourJSON .keys();
    while(keysIterator.hasNext()) {
       String key = keysIterator.next();
       JSONObject actualObj = (JSONObject)yourJSON.get(key);
       //Here, supposing you had defined Item class, using Gson, you'd do this:
       Item thisItem = (new Gson()).fromJson(actualObj.toString(), Item.class);
       //From here you can call thisItem.getEntityId(), etc 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多