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

有人可以提供一个示例或引用,它提供了一种方法,可以使用Jackson库将嵌套JAVA对象转换为JSON输出.我没有转换平面JAVA对象的问题.但是,JSON库显示嵌套对象名称和类型而不是其子对象.我几乎利用了http://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/提供的相同代码.所以我没有附上任何代码示例.

例如

// This is what I get
{
"fname":null,
"lname":null,
"addr":null
}


// This is what I need as output
{
"name":null,
"lname":null,
"addr":{
    street:"mull",
    "city":null,
    "zip":0
}
}

这个示例类对象:

import address;

public class id implements Serializable {
public String fname;
public String lname;
public address addr; 

} 

public class address implements Serializable {
public String street;
public String city; 
public int zip;
}

解决方法:

创建一个类地址.

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
  }
}
上一篇:AWS::Serverless::Application


下一篇:python – 访问嵌套字典中的值