Java – JSON Formatting with Jersey and Jackson

jacksonjavajersey

Using Java 6, Tomcat 7, Jersey 1.15, Jackson 1.9.9, created a simple web service which has the following architecture:

My POJOs (model classes):

Family.java:

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Family {

    private String father;
    private String mother;

    private List<Children> children;

    // Getter & Setters
}

Children.java:

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Children {

    private String name;
    private String age;
    private String gender;

    // Getters & Setters
}

Using a Utility Class, I decided to hard code the POJOs as follows:

public class FamilyUtil {
    public static Family getFamily() {
        Family family = new Family();
        family.setFather("Joe");
        family.setMother("Jennifer");

        Children child = new Children();
        child.setName("Jimmy");
        child.setAge("12");
        child.setGender("male");
        List<Children> children = new ArrayList<Children>();

        children.add(child);

        family.setChildren(children);
        return family;
    }
}

MyWebService:

@Path("")
public class MyWebService {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Family getFamily {
        return FamilyUtil.getFamily();
    }
}

Produces:

{"children": [{"age":"12","gender":"male","name":"Jimmy"}],"father":"Joe", "mother":"Jennifer"}

What I need to do is have it produce it in a more legible manner:

{ 
    "father":"Joe", 
    "mother":"Jennifer",
    "children": 
    [
        {
            "name":"Jimmy",
            "age":"12","
            "gender":"male"
        }
    ]
}

Just am seeking a way to implement so it can display some type of formatting with indentation / tabs.

Would be very grateful if someone could assist me.

Thank you for taking the time to read this.

Best Answer

Instead of returning a Family, you can just return a String (the web service caller won't notice a difference)

@Path("")
public class MyWebService {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getFamily {
        // ObjectMapper instantiation and configuration could be static...
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); 
        return mapper.writeValueAsString(FamilyUtil.getFamily());
    }
}

Although, as I said in my comment to your question, your service really shouldn't be doing this. It should be up to the web service caller to format the response into whatever format they need.