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?

3
  • 3
    what have you tried so far? what JSON library are you using? Commented Apr 17, 2019 at 6: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 How to Ask. Commented Apr 17, 2019 at 6:28
  • 1
    Possible duplicate of How to convert the following json string to java object? Commented Apr 17, 2019 at 6:30

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.