Create simple JSON structure using jackson

jackson, java, json

Solution

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.

Problem

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 ?

Original source