[英]How do I create an object from a JSON string using Jackson's ObjectMapper?
I have classes structured in the following way:我的课程结构如下:
@JsonRootName("class1")
public class class1 {
private interface1 foo;
public interface1 getFoo() {
return foo;
}
public void setFoo(interface1 foo) {
this.foo = foo;
}
}
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({@JsonSubTypes.Type(value = class2.class, name = "class2")})
public interface interface1 {
String getType();
}
@JsonTypeName("class2")
public class class2 implements interface1 {
private String buzz = "bar";
@Override
public String getType() {
return "class2";
}
public String getBuzz() {
return buzz;
}
public void setBuzz(String buzz) {
this.buzz = buzz;
}
}
If I parsed the following JSON into class1 using the ObjectMapper
it would be fine:如果我使用ObjectMapper
将以下 JSON 解析为 class1 就可以了:
{
"class1": {
"foo": {
"class2": {
"buzz": "not bar"
}
}
}
}
In this example the buzz variable in the class2 object would be set to "not bar" and the foo variable in the class1 would be set to the class2 object.在此示例中,class2 object 中的 Buzz 变量将设置为“not bar”,而 class1 中的 foo 变量将设置为 class2 object。
If I didn't want to modify the buzz
variable in class2
and just wanted the foo variable in class1
to be set to a plain class2
object, how would I do that?如果我不想修改class2
中的buzz
变量,而只想将class1
中的 foo 变量设置为普通的class2
object,我该怎么做? The following doesn't work since "class2"
is interpreted as a string:由于"class2"
被解释为字符串,因此以下内容不起作用:
{
"class1": {
"foo": "class2"
}
}
Same as the first example, but without the buzz
field.与第一个示例相同,但没有buzz
字段。
{
"class1": {
"foo": {
"class2": {
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.