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


    一、意义

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

    1实体类转JSON

    1. public static void main(String[] args) throws JsonProcessingException {
    2. user user = new user();
    3. user.setId(1001);
    4. user.setUsername("张三");
    5. user.setPassword("123456");
    6. user.setTeach(false);
    7. System.out.println(user);
    8. ObjectMapper objectMapper=new ObjectMapper();
    9. String value = objectMapper.writeValueAsString(user);
    10. System.out.println(JSON.toJSONString(user));
    11. System.out.println(value);
    12. }

    结果:

    2JSON转实体类

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

    需要注意的是如果我们的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则不存在这个问题,会自动给忽略不存在的属性

     结果:

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

  • 相关阅读:
    lvm + raid(逻辑磁盘+阵列)创建删除恢复 for linux
    优先级反转那些事儿
    技巧分享:简单的流程图怎么作?
    vue手动拖入和导入excel模版
    数据库基础知识
    vue组件间的通讯方式
    通过mxGraph在ARMxy边缘计算网关上实现工业物联网
    为什么 ConcurrentHashMap 中 key 不允许为null
    RPA流程调试:准确定位错误原因及位置
    OA问题的解决方法
  • 原文地址:https://blog.csdn.net/m0_75015491/article/details/132859202