JSON 对象数组到 Java POJO

Rud*_*udy 7 java arrays json object

将此 JSON 对象转换为 Java 中的类,映射在您的 POJO 类中如何?

{
    "ownerName": "Robert",
    "pets": [
        {
            "name": "Kitty"
        },
        {
            "name": "Rex"
        },
        {
            "name": "Jake"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ber 11

这种问题很受欢迎,需要一般性的回答。如果您需要POJO基于JSONJSON Schema使用www.jsonschema2pojo.org生成模型。示例打印屏幕显示了如何使用它: 在此处输入图片说明

如何使用它:

  1. 选择目标语言。Java在你的情况下。
  2. 选择来源。JSON在你的情况下。
  3. 选择注释样式。这可能很棘手,因为它取决于您要用于序列化/反序列化的库JSON。如果模式很简单,请不要使用注释(None选项)。
  4. 选择其他可选配置选项,如Include getters and setters. 你也可以这样做IDE
  5. 选择Preview按钮。如果模式是ZIP带有生成类的大下载。

为您的JSON这个工具生成:

public class Person {

 private String ownerName;
 private List <Pet> pets = null;

 public String getOwnerName() {
  return ownerName;
 }

 public void setOwnerName(String ownerName) {
  this.ownerName = ownerName;
 }

 public List < Pet > getPets() {
  return pets;
 }

 public void setPets(List < Pet > pets) {
  this.pets = pets;
 }

}

public class Pet {

 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}
Run Code Online (Sandbox Code Playgroud)

对于Android StudioKotlin阅读RIP http://www.jsonschema2pojo.org