将嵌套的Java对象转换为Jackson JSON

将嵌套的Java对象转换为Jackson JSON,第1张

嵌套的Java对象转换为Jackson JSON

创建一个类地址。

public class Address {    private String street;    private String city;     private int zip;    public String getStreet() {        return street;    }    public void setStreet(String street) {        this.street = street;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }    public int getZip() {        return zip;    }    public void setZip(int zip) {        this.zip = zip;    }}

创建一个类别ID。

 public class Id {    private String fname;    private String lname;    private Address addr;    public String getFname() {        return fname;    }    public void setFname(String fname) {        this.fname = fname;    }    public String getLname() {        return lname;    }    public void setLname(String lname) {        this.lname = lname;    }    public Address getAddr() {        return addr;    }    public void setAddr(Address addr) {        this.addr = addr;    }}

主要方法:

import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;public class Test {    public static void main(String[] args) {        Address addressObj = new Address();        addressObj.setCity("Chicago");        addressObj.setStreet("Some Street");        addressObj.setZip(12345);        Id idObj = new Id();        idObj.setAddr(addressObj);        idObj.setFname("Test");        idObj.setLname("Tester");        ObjectMapper mapper = new ObjectMapper();        //Object to JSON in String        try { String jsonInString = mapper.writerWithDefaultPrettyPrinter().writevalueAsString(idObj); System.out.println(jsonInString);        } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace();        }}}

输出

{  "fname" : "Test",  "lname" : "Tester",  "addr" : {    "street" : "Some Street",    "city" : "Chicago",    "zip" : 12345  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4910815.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存