bbboomer bbboomer - 20 days ago 6x
JSON Question

Convert nested java objects to Jackson JSON

Could someone provide an example or reference that provides a way to convert a nest JAVA object to JSON output using Jackson libraries preferably. I have no problem converting a flat JAVA object. However the JSON libraries show the nested object name and type rather than its sub-objects. I'm pretty much leveraging the same code provided here . So I'm not attaching any code example.


// This is what I get

// This is what I need as output

This the sample class objects:

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;


Create a class Address.

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) { = city;
    public int getZip() {
        return zip;
    public void setZip(int zip) { = zip;

Create a class 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;

Main method:

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.setStreet("Some Street");

        Id idObj = new Id();

        ObjectMapper mapper = new ObjectMapper();

        //Object to JSON in String
        try {
            String jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(idObj);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block


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