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 ?
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.
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.
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.
Right. The code needed:
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(new Status()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With