使用jackson创建简单的JSON结构 [英] Create simple JSON structure using jackson
问题描述
我想创建相当于以下内容的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;
}
}
但是我如何实例化然后编写JSON到一个字符串?
But how do I instatiate it and then write the JSON to a string ?
推荐答案
您的示例和Jackson的问题是JSON属性名称的默认选择:Jackson将看到 isDone
和 setDone
并选择 done
作为JSON属性名称。您可以使用 JsonProperty
注释覆盖此默认选项:
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;
}
}
然后:
Status instance = new Status();
String jsonString = null;
instance.setDone(true);
ObjectMapper mapper = new ObjectMapper();
jsonString = mapper.writeValueAsString(instance);
现在 jsonString
包含 {isDone:true}
。请注意,您还可以使用 OutputStream 杰克逊/图/ ObjectMapper.html#writeValue%28java.io.OutputStream,%20java.lang.Object%29\" 相对= nofollow> ObjectMapper.writeValue(OutputStream中,对象)或至 Writer
使用 ObjectMapper.writeValue(Writer,Object)。
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).
在这种情况下你实际上只需要在任一访问者上使用 JsonProperty
注释,但不能同时使用两者。只需注释 isDone
即可获得所需的JSON属性名称。
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.
使用<$ c的替代方法$ c> JsonProperty 注释是重命名访问者 setIsDone / getIsDone
。然后注释是不必要的。
An alternative to using the JsonProperty
annotation is to rename your accessors setIsDone/getIsDone
. Then the annotations are unnecessary.
查看快速而肮脏的Jackson教程:杰克逊在5分钟内完成。通过查看Jackson注释的文档来了解特定属性。
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.
这篇关于使用jackson创建简单的JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!