Amir Hossein Hadian
Amir Hossein Hadian

Reputation: 9

how to convert a json file to some object calsses

I have a json file like this:

{
  "Student" : [
  {
    "name": "john",
    "age": 12
  }, {
    "name": "jack",
    "age": 20
  }
  ]
}

and my Student class is:

public class Student {
private String name;
private int age;

public Student(String name, int age) {
    this.name = name;
    this.age = age;
}

public String getName() {
    return name;
}

public int getAge() {
    return age;
}

}

I want to make a Student Instance with name "jack" by using json how can I do it?

Upvotes: 0

Views: 80

Answers (2)

Daniel Jabłoński
Daniel Jabłoński

Reputation: 25

I use org.json.simple library when I parse JSON Excample: excample App.java, excample Information.java

List<Information> parseInformationObject(JSONArray infoList) {
        List<Information> in = new ArrayList<>();

        infoList.forEach(emp -> {

            JSONObject info = (JSONObject) emp;

            String id = info.get("id").toString();
            String state = info.get("state").toString();
            String type = null;
            if (info.get("type") != null) {
                type = info.get("type").toString();
            }
            String host = null;
            if (info.get("host") != null) {
                host = info.get("host").toString();
            }
            long timestamp = (long) info.get("timestamp");

            in.add(new Information(id, state, type, host, timestamp));

        });
        return in;
    }

Upvotes: 0

Khalid Shah
Khalid Shah

Reputation: 3232

Make Another Class Students which contain List<Student>.

public class Students { 
  List<Student> Student;

  public List<Student> getStudents() {
    return Student;
  }

  public void setStudent(List<Student> students) {
     this.Student=students;
  }

}

Gson gson = new Gson();
String jsonString = "Your Json String";
Students student = gson.fromJson(jsonString, Students.class);

Upvotes: 2

Related Questions