0

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);
}
2
  • What are you looking for? Commented Jul 18, 2016 at 16:14
  • how to build model class? Commented Jul 19, 2016 at 6:14

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Correct. I'm a bit concerned with childrens, though ;)
yah children seem more English, developers again at it... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.