简体   繁体   English

如何为包含单个字段和数组的JSON创建POJO?

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

I have the following JSON : 我有以下JSON

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

How can I create a Java POJO for this? 如何为此创建Java POJO I am not sure how to do so as it contains a single field (username) and also an array . 我不确定如何执行此操作,因为它包含一个字段(用户名)和一个array

With this you can generate your POJO 这样您就可以生成您的POJO

http://www.jsonschema2pojo.org http://www.jsonschema2pojo.org

You can use google's Gson library 您可以使用Google的Gson库

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. 基本上代表Array的是编写一个自定义类,并在您的Response类中创建该自定义类的数组并使用它。

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 并始终使用http://www.jsonschema2pojo.org进行pojo创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM