0

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?

Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87
  • 3
    what have you tried so far? what JSON library are you using? – Scary Wombat Apr 17 '19 at 06:24
  • It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – Rcordoval Apr 17 '19 at 06:28
  • 1
    Possible duplicate of [How to convert the following json string to java object?](https://stackoverflow.com/questions/10308452/how-to-convert-the-following-json-string-to-java-object) – Pavel Smirnov Apr 17 '19 at 06:30

2 Answers2

2

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);
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
0

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