如何忽略JSON中的父标签?
以下是我的JSON:
String str = "{\"parent\": {\"a\":{\"id\": 10, \"name\":\"Foo\"}}}";
这里是从json映射的类。
public class RootWrapper {
private List<Foo> foos;
public List<Foo> getFoos() {
return foos;
}
@JsonProperty("a")
public void setFoos(List<Foo> foos) {
this.foos = foos;
}
}
以下是测试代码:
public class JacksonTest {
// code here
}
@Test
public void wrapRootValue() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String str = "{\"parent\": {\"a\":{\"id\": 10, \"name\":\"Foo\"}}}";
RootWrapper root = mapper.readValue(str, RootWrapper.class);
Assert.assertNotNull(root);
}
我遇到了这个错误:
org.codehaus.jackson.map.JsonMappingException: Root name 'parent' does not match expected ('RootWrapper') for type [simple type, class MavenProjectGroup.mavenProjectArtifact.RootWrapper]
我发现了Jackson注解提供的解决方案:
(a) Annotate you class as below
@JsonRootName(value = "parent")
public class RootWrapper {
(b) It will only work if and only if ObjectMapper is asked to wrap.
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
任务完成!
Jackson反序列化方式又出了问题 :(
如果配置了'DeserializationConfig.Feature.UNWRAP_ROOT_VALUE',它将解包所有的JSONs,即使我的类没有用@JsonRootName(value =“rootTagInJson”)注释,这不奇怪吗。
我希望只有当类使用@JsonRootName进行注释时才解包根标记,否则不要解包。
因此,以下是解包根标记的用例。
###########################################################
Unwrap only if the class is annotated with @JsonRootName.
############################################################
我在Jackson源代码的ObjectMapper中做了一个小改动,并创建了一个新版本的jar。 1. 将此方法放置在ObjectMapper中
// Ash:: Wrap json if the class being deserialized, are annotated
// with @JsonRootName else do not wrap.
private boolean hasJsonRootName(JavaType valueType) {
if (valueType.getRawClass() == null)
return false;
Annotation rootAnnotation = valueType.getRawClass().getAnnotation(JsonRootName.class);
return rootAnnotation != null;
}
2. Edit ObjectMapper method ::
Replace
cfg.isEnabled(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE)
with
hasJsonRootName(valueType)
3. Build your jar file and use it.
Map<String,WrappedType>
然后获取唯一条目的值。 - StaxManmyClientResponse.getEntity(new GenericType<Map<String, WrappedType>>(){});
- pulkitsinghal