本文主要是介绍Jackson简单使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Jackson简单使用
1 对象转json串
1.创建数据对象
@Data //lombok
public class User {private String name;private String sex;
}
2.代码
public static void main(String[] args) throws JsonProcessingException {User user = new User();user.setName("名字");user.setSex("性别");ObjectMapper objectMapper = new ObjectMapper();String json = objectMapper.writeValueAsString(user);System.out.println(json); //{"name":"名字","sex":"性别"}}
2.json转对象
public static void main(String[] args) throws IOException {String json = "{\"name\":\"名字\",\"sex\":\"性别\"}";ObjectMapper objectMapper = new ObjectMapper();User user = objectMapper.readValue(json,User.class);System.out.println(user);//User(name=名字, sex=性别)}
3.对象转Map
首先把对象转成json字符串,然后转map
public static void main(String[] args) throws IOException {User user = new User();user.setName("名字");user.setSex("性别");ObjectMapper objectMapper = new ObjectMapper();Map<String, Object> map = objectMapper.readValue(objectMapper.writeValueAsString(user), Map.class);System.out.println(map);//{name=名字, sex=性别}}
4.对象转Map过滤值为null
我们给数据对象新增一个属性age
@Data
@ToString
public class User {private String name;private String sex;private Integer age;}
在转成Map时候结果为:
要过滤值为null只需要添加注解:@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {private String name;private String sex;private Integer age;}
再次转Map:
5.过滤null转空字符串
ObjectMapper objectMapper = new ObjectMapper();objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {@Overridepublic void serialize(Object arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException, JsonProcessingException {arg1.writeString("");}});
这篇关于Jackson简单使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!