我有以下Json
public class User {
private String name;
private int age;
// getters & setters
}
我想要反序列化为类的实例
@JsonRootName
为此,我在类名上使用了@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.featuresToEnable(DeserializationFeature.UNWRAP_ROOT_VALUE);
return builder;
}
}
,如下所示
{
"name": "Ram",
"age": 27
}
但它没有按预期工作。如果我发送类似下面的内容,那就有用了。
jQuery.validator.addMethod("hasAttributes", function(value, element) {
console.log('bla');
return $("ul > li").length > 0
})
console.log($("#templateForm").validate({
ignore: "",
rules: {
attr: {hasAttributes: true}
},
submitHandler: function (form) { // for demo
alert(this.valid()); // for demo
return false; // for demo
},
invalidHandler: function(event, validator) { alert('oops, no attributes'); }
}));
$("#templateForm").valid()
但是我希望用根名称对json进行反序列化。任何人都可以建议吗?
我想以这种方式开始启动。
答案 0 :(得分:0)
使用 ObjectMapper ,您可以轻松解决此问题。这是你要做的: - 注释用户类,如下所示
@JsonRootName("user")
public class User {
private String name;
private int age;
// getters & setters
}
创建CustomJsonMapper类
公共类CustomJsonMapper扩展了ObjectMapper {
private DeserializationFeature deserializationFeature;
public void setDeserializationFeature (DeserializationFeature deserializationFeature) {
this.deserializationFeature = deserializationFeature;
enable(this.deserializationFeature);
}
} // This is spring configuration /*<bean id="objectMapper"
class=" com.cognizant.tranzform.notification.constant.CustomJsonMapper">
<property name="deserializationFeature" ref="deserializationFeature"/>
</bean>
<bean id="deserializationFeature" class="com.fasterxml.jackson.databind.DeserializationFeature"
factory-method="valueOf">
<constructor-arg>
<value>UNWRAP_ROOT_VALUE</value>
</constructor-arg>
</bean>*/
使用以下代码可以测试
ApplicationContext context = new ClassPathXmlApplicationContext( “applicationContext.xml中”); ObjectMapper objectMapper =(ObjectMapper)context .getBean( “objectMapper”); String json =“{\”user \“:{\”name \“:\”Ram \“,\”age \“:27}}”; 用户user = objectMapper.readValue(json,User.class);
答案 1 :(得分:0)
@JsonRootName
是一个好的开始。在User
类上使用此批注,然后通过添加以下内容启用UNWRAP_ROOT_VALUE
反序列化功能:
spring.jackson.deserialization.UNWRAP_ROOT_VALUE=true
到application.properties
。
阅读有关在Spring Boot Reference