Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create simple JSON structure using jackson

Tags:

java

json

jackson

I'd just like to create the Jackson mapping equivalent of the below :

{\"isDone\": true}

I think I need to create a class like this :

public class Status {

    private boolean isDone;

    public boolean isDone{
        return this.isDone;
    }

    public void setDone(boolean isDone){
        this.isDone = isDone;
    }
}

But how do I instatiate it and then write the JSON to a string ?

like image 908
user701254 Avatar asked Jun 19 '12 22:06

user701254


People also ask

How does Jackson build JSON?

We can create a JSON in the Jackson library using the JsonNodeFactory, it can specify the methods for getting access to Node instances as well as the basic implementation of the methods. We can use the set() and put() methods of ObjectNode class to populate the data.

How do you create an ArrayNode?

Creating an Array Object var array = []; Option two is to create an Array object by instantiating the Array object. var array = new Array(); The last option is to create an Array object by inserting collection data.


2 Answers

A problem with your example and Jackson is the default choices of JSON property names: Jackson will see isDone and setDone and choose done as the JSON property name. You can override this default choice using the JsonProperty annotation:

public class Status
{
    private boolean isDone;

    @JsonProperty("isDone")
    public boolean isDone()
    {
        return this.isDone;
    }

    @JsonProperty("isDone")
    public void setDone(boolean isDone)
    {
        this.isDone = isDone;
    }
}

Then:

Status instance = new Status();
String jsonString = null;

instance.setDone(true);
ObjectMapper mapper = new ObjectMapper();

jsonString = mapper.writeValueAsString(instance);

Now jsonString contains { "isDone" : true }. Note that you can also write the string to an OutputStream using ObjectMapper.writeValue(OutputStream, Object), or to a Writer using ObjectMapper.writeValue(Writer, Object).

In this case you really only need the JsonProperty annotation on either of your accessors, but not both. Just annotating isDone will get you the JSON property name that you want.

An alternative to using the JsonProperty annotation is to rename your accessors setIsDone/getIsDone. Then the annotations are unnecessary.

See the quick and dirty Jackson tutorial: Jackson in 5 minutes. Understanding of the specific properties came from looking through the docs for Jackson annotations.

like image 166
pb2q Avatar answered Oct 15 '22 18:10

pb2q


Right. The code needed:

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(new Status()));
like image 44
Istvan Devai Avatar answered Oct 15 '22 18:10

Istvan Devai