Creating a simple JSON structure using jackson

I would like to create an equivalent Jackson mapping below:

{\"isDone\": true}

It seems to me that I need to create a class as follows:

public class Status {

    private boolean isDone;

    public boolean isDone{
        return this.isDone;
    }

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

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

+5
source share
2 answers

The problem with your example and Jackson is the default choice for JSON property names: Jackson will see isDoneand setDoneand select doneJSON as the property name. You can override this default selection using the annotation JsonProperty:

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);

jsonString { "isDone" : true }. , OutputStream ObjectMapper.writeValue(OutputStream, Object) Writer, ObjectMapper.writeValue(Writer, Object).

JsonProperty , . isDone JSON, .

JsonProperty setIsDone/getIsDone. .

: 5 . .

+6

Right Required Code:

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(new Status()));
+2
source

All Articles