jackson第二篇

    科技2026-02-16  11

    一、从URL读取JSON数据

    请求远程的API,获得远程服务的JSON响应结果,并将其转换为Java POJO对象。

    @Test void testURL() throws IOException { URL url = new URL("https://jsonplaceholder.typicode.com/posts/1"); //远程服务URL ObjectMapper mapper = new ObjectMapper(); //从URL获取JSON响应数据,并反序列化为java 对象 PostDTO postDTO = mapper.readValue(url, PostDTO.class); System.out.println(postDTO); }

    注:如果不知道具体的反序列化对象是什么样的,可以把数据存到map中

    Map postDTO = mapper.readValue(url, Map.class);

    二、忽略某个字段

    @JsonIgnore public class { public int value; @JsonIgnore public int internalValue; } disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) //返回JSON格式的数据忽略某个字段(对应的实体中没有对应字段) @Data public class PlayerStar { @JsonProperty("playerName") private String name; private Integer age; private String[] hobbies; //业余爱好,数组 private List<String> friends; // 朋友 private Map<String, BigDecimal> salary; //年收入 Map } @Data public class PlayerStar2 { @JsonProperty("playerName") private String name; // private Integer age; private String[] hobbies; //业余爱好,数组 private List<String> friends; // 朋友 private Map<String, BigDecimal> salary; //年收入 Map } @Test public void testUnKnowProperties() throws IOException { ObjectMapper mapper = new ObjectMapper(); PlayerStar player = PlayerStar.getInstance(); //将PlayerStar序列化为对象 String valueAsString = mapper.writeValueAsString(player); log.info(valueAsString); //报错:JSON字符串所包含的属性,多余的Java类的定义(多出一个阿年龄,赋值时找不到setAge方法) //忽略掉age属性,不接受我们的java类未定义的成员变量数据 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); PlayerStar2 playerStar2 = mapper.readValue(valueAsString, PlayerStar2.class); log.info(playerStar2.toString()); }

    三、未赋值Java Bean序列化

    如果某些类的数据可能为空,我们通常也不会为它赋值。但是客户端就是需要这个{}的JSON对象

    public class MyEmptyObject { private Integer i; //没有get set方法 }

    可以为ObjectMapper设置disable序列化特性:FAIL_ON_EMPTY_BEANS,也就是允许对象的所有属性均未赋值。

    @Test void testEmpty() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); String jsonString = mapper.writeValueAsString(new MyEmptyObject()); System.out.println(jsonString); }

    四、日期格式化

    ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); //注意这里 mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); //注意这里 Map temp = new HashMap(); temp.put("now", new Date()); String s = mapper.writeValueAsString(temp); System.out.println(s); 还可以使用注解:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")

    我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3vtuwevgbfms4

    Processed: 0.024, SQL: 9