【问题标题】:Remove unwanted information in gson JsonObject删除 gson JsonObject 中不需要的信息
【发布时间】:2017-05-09 02:47:34
【问题描述】:

我有一个JSONObject 回复,比如

{
    "0:"{
        "name": "name1",
        "surname": "surname1",
        "id": "22",
        "motivations": []
    },
    "1:"{
        "name": "name2",
        "surname": "surname2",
        "id": "23",
        "motivations": []
    },
    "2:"{
        "name": "name3",
        "surname": "surname3",
        "id": "24",
        "motivations": []
    },
    "sign": "9e46b7d6b140b",
    "last_call": 1446
}

我想将其映射到 List<Person> ,但在我擦除之前我无法做到 "0:","1:","2:" ,"sign":"9e46b7d6b140b","last_call":1446.

知道如何在模型中映射它吗?

【问题讨论】:

  • 我猜想改变你的 API。
  • JSON 格式的 t 是完全错误的。为了让您能够使用 GSON,它必须包含 Person 对象数组
  • 所以是 api 故障?还是我需要对其进行不同的解码?

标签: android parsing gson retrofit


【解决方案1】:

创建Person

class Person{
        String name;
        String surname;
        String id;
        String[] motivations;
         //Create getter setter for it
    }

创建HashMap<String,Object> map = new HashMap<>();

map = new Gson().fromJson(responseData, HashMap.class);

最后一次迭代地图

Iterator entries = map .entrySet().iterator();

while (entries.hasNext()) {
   String value = (String )entries.next().getValue();
 Object p;
 try{ 
    p = new Gson().fromJson(value , Person .class);
    \\person class
  }
  catch(Exception e)
  {
    // catch exception
    p =null;
  }
  if(p!= null && p instanceOf Person)
  {
     \\create list and add it to the separate list 
    \\ entries.next().getKey()
    \\ entries.next().getValue()
  }
}

【讨论】:

  • 我无法实现entry.next().getValue(); (无法解析)HashMap map = new Gson().fromJson(response.body(), HashMap.class);迭代器条目 = map .entrySet().iterator(); while (entries.hasNext()) { String value = (String )entries.next().getValue(); Log.i(TAG,"cos ma"+值); entry.next(); }
  • @Expiredmind,请与stackoverflow.com/questions/1066589/iterate-through-a-hashmap联系,我认为这会对您有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 2020-09-28
  • 2018-10-07
  • 2022-11-17
  • 1970-01-01
相关资源
最近更新 更多