JSON与实体类之间的互相转换!!

一、意义

在我们调用三方平台接口时,经常需要将我们封装的实体类转换为json作为传参,或者是当我们接收报文时接收的为json数据想要转换为我们自己封装的实体类。

1实体类转JSON

  public static void main(String[] args) throws JsonProcessingException {
         user user = new user();
         user.setId(1001);
         user.setUsername("张三");
         user.setPassword("123456");
         user.setTeach(false);
        System.out.println(user);
        ObjectMapper objectMapper=new ObjectMapper();
         String value = objectMapper.writeValueAsString(user);
        System.out.println(JSON.toJSONString(user));
        System.out.println(value);
    }

结果:

2JSON转实体类

    public static void main(String[] args) throws JsonProcessingException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",1001);
        jsonObject.put("username","张三");
        jsonObject.put("teach","false");
        jsonObject.put("password","123456");
        jsonObject.put("student","1");
        ObjectMapper objectMapper=new ObjectMapper();
        user user = objectMapper.readValue(jsonObject.toString(), user.class);
        System.out.println(user);
    }

需要注意的是如果我们的json数据有五个字段而实体类中只有四个字段的话无法一 一映射会报错

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "student" (class com.newstart.model.user), not marked as ignorable (4 known properties: "id", "teach", "username", "password"])
 at [Source: (String)"{"password":"123456","student":"1","teach":"false","id":1001,"username":"张三"}"; line: 1, column: 33] (through reference chain: com.newstart.model.user["student"])

 

所以我们需要在对应的实体类上加一个注解

@JsonIgnoreProperties(ignoreUnknown = true)

该注解的作用是在将实体类进行json序列化和反序列化时可以将无法映射的属性忽略,针对的是jackson。如果fastjson则不存在这个问题,会自动给忽略不存在的属性

 结果:

此外还有很多种转换方式!!!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山川志~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值