JSON对象到Java POJO的数组 [英] Array of JSON Object to Java POJO

查看:365
本文介绍了JSON对象到Java POJO的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Converting this JSON object as a class in java, how would the mapping be in your POJO Class?

{
    "ownerName": "Robert",
    "pets": [
        {
            "name": "Kitty"
        },
        {
            "name": "Rex"
        },
        {
            "name": "Jake"
        }
    ]
}

推荐答案

这种问题非常流行,需要一般性回答.如果您需要基于JSONJSON Schema生成POJO模型,请使用 www.jsonschema2pojo.org .打印屏幕示例显示了如何使用它:

This kind of question is very popular and needs general answer. In case you need generate POJO model based on JSON or JSON Schema use www.jsonschema2pojo.org. Example print screen shows how to use it:

如何使用它:

  1. 选择目标语言. Java您的情况.
  2. 选择来源. JSON您的情况.
  3. 选择注释样式.这可能很棘手,因为它取决于要用于序列化/反序列化JSON的库.如果架构很简单,请不要使用注释(None选项).
  4. 选择其他可选配置选项,例如Include getters and setters.您也可以在IDE中完成该操作.
  5. 选择Preview按钮.如果架构很大,请下载具有生成类的ZIP.
  1. Select target language. Java in your case.
  2. Select source. JSON in your case.
  3. Select annotation style. This can be tricky because it depends from library you want to use to serialise/deserialise JSON. In case schema is simple do not use annotations (None option).
  4. Select other optional configuration options like Include getters and setters. You can do that in your IDE as well.
  5. Select Preview button. In case schema is big download ZIP with generated classes.

此工具为您的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;
 }
}

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

这篇关于JSON对象到Java POJO的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆