简体   繁体   中英

GSON to parse a JSON array

I have a JSON file like this:

[
  {
    "id": "1",
    "name": "test1",
    "childrens": [
      {
        "id": "14",
        "name": "test2",
        "childrens": [

        ]
      }
    ]
  }
]

The model class:

public class Model {

   private int id;
   private String name;
}

And my parse method:

public List< Model > parseJSONService(JSONArray jsonArray) {

    Gson gson = new Gson();
    Model[] model = gson.fromJson(jsonArray.toString(),
            Model[].class);
    return Arrays.asList(model);
}

why not parse the json string directly? this is what i did, achieved the same thing you looking for i guess:

public class GsonPlay {


    public static void main(String args[]) {

        String testString = "[{\"id\": \"1\",\"name\": \"test1\",\"childrens\": [{\"id\": \"14\",\"name\": \"test2\",\"childrens\": []}]}]";
        List<Model> modelList = parseJsonService(testString);
        System.out.println(modelList);
    }

    private static List<Model> parseJsonService(String testString) {
        Gson gson = new Gson();
        Model[] models = gson.fromJson(testString, Model[].class);
        return Arrays.asList(models);
    }
}
class Model {
    private int id;
    private String name;
    private List<Model> childrens;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Model> getChildrens() {
        return childrens;
    }

    public void setChildrens(List<Model> childrens) {
        this.childrens = childrens;
    }
}

You can also have a look at this for further ideas:

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