简体   繁体   中英

Parsing specific JSON with Gson

I'm currently trying to parse a JSON response with the following structure using Gson:

{
  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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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