简体   繁体   English

用Gson解析特定的JSON

[英]Parsing specific JSON with Gson

I'm currently trying to parse a JSON response with the following structure using Gson: 我目前正在尝试使用Gson使用以下结构解析JSON响应:

{
  data {
   "1": {
      "name": "John Doe"
  },
   "2": {
      "name": "John Doe"
  },
  ...
}

My response class: 我的回答是:

class Response {
  Map<String, ModelObj> data;
}

and model class: 和模型类:

class ModelObj {
  String name;
}

But what I can't figure out is how to simply map everything to a single List where the id is placed within the ModelObj without having them separate as key/value pairs in a Map. 但是我不知道的是如何简单地将所有内容映射到一个ID放在ModelObj中的列表,而不将它们作为Map中的键/值对分开。 So ideally my response class would be: 因此,理想情况下,我的响应类是:

class Response {
  List<ModelObj> data;
}

and model class: 和模型类:

class ModelObj {
  String id;
  String name;
}

How would this be accomplished? 这将如何实现?

 [
   {
        "id": 1,
        "name": "John Doe"
    }, 
    {
        "id": 2,
        "name": "John Doe"
    }
 ]

If your response is of above form then only you will get the list of model object and you will get Array of ModelObj 如果您的回答是以上形式,那么只有您将获得模型对象列表,并且将获得ModelObj数组

then use below code to convert to List 然后使用下面的代码转换为列表

 public <T> List<T> getObjectToList(String json, Class<T[]> ObjectArrayClass) { return Arrays.asList(gson.fromJson(json, ObjectArrayClass)); } 
List< ModelObj > arrayList = getObjectToList(jsonResponseString, ModelObj[].class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM