目的:都是为了解决json字符串的某些属性名和JavaBean中的属性名匹配不上的问题。
-
JsonProperty
-
public class User { @JsonProperty("JsonPropertyName") private String name; private String sex; private Integer age; //get/setter与tostring正常字段名:name、sex、age }
-
@Test public void testJsonProperty() throws IOException{ User user=new User("shiyu","man",22); System.out.println(new ObjectMapper().writeValueAsString(user)); String str="{\"sex\":\"man\",\"age\":22,\"JsonPropertyName\":\"shiyu\"}"; System.out.println(new ObjectMapper().readValue(str,User.class).toString()); } 输出: {"sex":"man","age":22,"JsonPropertyName":"shiyu"} User [name=shiyu, sex=man, age=22]
-
-
JSONField
-
public class User { @JSONField(name="JSONFieldName") private String name; private String sex; private Integer age; //get/setter与tostring正常字段名:name、sex、age }
-
@Test public void testSONField(){ User user=new User("shiyu","man",22); System.out.println(JSON.toJSONString(user)); String str="{\"JSONFieldName\":\"shiyu\",\"age\":22,\"sex\":\"man\"}"; System.out.println(JSON.parseObject(str, User.class).toString()); } 输出 {"JSONFieldName":"shiyu","age":22,"sex":"man"} User [name=shiyu, sex=man, age=22]
-