简体   繁体   中英

How to create POJO for JSON that contains a single field and an Array?

I have the following JSON :

{
    "userName":"<string>",
    "persons": [
        {
            "id":"<number>",
            "name":"<string>"
        }
    ]
}

How can I create a Java POJO for this? I am not sure how to do so as it contains a single field (username) and also an array .

With this you can generate your POJO

http://www.jsonschema2pojo.org

You can use google's Gson library

public class ClassName {
    private String username;
    private person[] persons;

    public ClassName(String username, person[] persons) {
        this.username = username;
        this.persons = persons;
    }

    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonStr;
        // To parse json string :
        ClassName className = gson.fromJson(jsonStr, ClassName.class);

        // using json file
        ClassName className = gson.fromJson(new FileReader("path to file"), ClassName.class);
    }
}

class Person {
    private int id;
    private string name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
Class JsonResposne{
String userName;
Persons[] persons;
//Getter & Setter , equals , toString methods go here
}

class Persons{
String id;
String name;
//Getter & Setter , equals , toString methods go here
}

Basically to represent the Array write a custom class, and create an array of the custom class in your Response class and use it.

create a single class like this

public class Pojo{
    private String userName;
    private List<Person> persons;

    //Getters and Setters

   //Inner Class
   public class Person{
       private Integer id;
       private String name;

       //Getters and Setters
   }

}

and always use http://www.jsonschema2pojo.org for pojo creation

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