zoukankan      html  css  js  c++  java
  • 【JSON】

    一、JSON格式入门

            基础类型: false / null / true / object / array / number / string

      几种形式:
        1、JSONArray:  见employees字段

        2、JSONString: company字段

        3、JSONObject:

            

      格式化工具

        1、https://jsoneditoronline.org/

        2、转义网站:https://www.sojson.com/yasuo.html 

    二、安全编码

      1、JsonSanitizer.sanitize(中文含义:杀毒)

       

      

    三、fastJson使用

      参考:http://kimmking.github.io/2017/06/06/json-best-practice/

      核心方法
        1. JSON.parseObject(jsonStr, xxx.class)  :将字符串转成Java类对象

        2. JSON.parseObject(jsonStr): 得到JSONObject,后续可使用getString(字段名)/getInteger(字段名)/getJSONArray(字段名)得到具体字段数值。

        3. JSON.toJSONString(JavaObject):  将Java对象,转成JSON格式字符串

      具体验证如下:

      pom.xml

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.32</version>
    </dependency>
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    </dependency>

      Bean定义:

            

       1、使用FastJson读写

             

             执行结果 

             

       2、将Java Bean尝试转JSON串

         

         打印:{"companyName":"AAA","employees":["bbb","ccc"],"mobile":888888}

      3、如果尝试转成其他Bean

    @Setter
    @Getter
    public class Model {
        private String name;
        private String value;
        private Integer mobile;
    }

        则java bean解析结果:仅mobile成功初始化(仅拼写相同的字段匹配)

          


     四、jackson使用

      JsonNode,是Jackson的json树模型

      参考:https://www.baeldung.com/jackson-object-mapper-tutorial

      方法:

        1、读json为Java对象:    objectMapper.readValue(数据源, Class) , 如转换读取Person对象,数据源包括URL/InputStream/String/Reader/File等

        2、读json为JsonNode:     objectMapper.readTree(数据源)方法,数据源包括URL/InputStream/String/Reader/File等

        3、写JsonNode至json:     objectMapper.writeValueAsString(Bean对象)方法,或其他适合你的写方法(writeValue),

        4、获取JsonNode:          1) jsonNode.get("field1");    2)使用at访问得到jsonNode:jsonNode.at("/identification/name")

        5、转换jsonNode:              asText/asDouble/asInt/asLong

      注解:

        @JsonIgnoreProperties(ignoreUnknown = true):  加在实体类上,目的:防止因传入的json字符串属性的缺少或过多超过Bean定义而JSON解析报错

    // Bean定义
    @JsonProperty("AAA") ---》 待转换JSON字符串中AAA的字段值被赋值给serverip private String serverip;

    1、简单对象

    String json = "{ "color" : "Black", "type" : "BMW" }";
    Map<String, Object> map 
      = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});

    2、JSON类型全是Map类型

      Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});

      或定义一个bean

    @Getter
    @Setter
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class CMDBUpdateNotificationBean {
    
        @JsonProperty("context")
        private Map<String, String> context;
    
        @JsonProperty("payload")
        private Map<String, String> payload;
    
    }

    3、JSON中包含复杂对象的数组场景

    String rawJsonStr = "{"currentPage":1,"objList":[{"mac_name":"eth0,lo","hard_disk":"40","memory":"15868","os":"EulerOS release 2.0 \u0028SP5\u0029","create_time":"2015-10-28 11:47:39","kernel":"3.10.0-862.14.1.5.h428.eulerosv2r7.x86_64","class_Id":1247,"ip":"10.21.0.44","resource_type":"hws_ecs","cpu":"8","remark":"","datacenter":6165801,"main_mac":"fa:16:3e:2c:a4:d0","net_interface":"eth0","check_status":"NORMAL","monitor_status":"已监控","start_time":"2021-09-17","hostname":"host-10-21-0-44","update_time":"2021-10-16 09:41:20","class_Name":"VMServer","assign_status":"INUSE","id":20,"last_Modified":1634377280284}],"pageSize":1,"totalNum":1,"totalPageNo":1}";
    Java Bean使用list的方式定义
    
    /**
     * 总页数
     */
    @JsonProperty("totalPageNo")
    private int totalPageNo;
    
    @JsonProperty("objList")
    private List<Server> serverList;
    
    解析
    
    ServerBatchResponse serverBatchResponse = null;
    serverBatchResponse = objectMapper.readValue(rawJsonStr, ServerBatchResponse.class);
    for (Server server : serverBatchResponse.getServerList()) {
       System.out.println(server.getHard_disk());
    }
    
    
  • 相关阅读:
    设计模式——迭代器模式
    FTP服务:FileZilla的配置和使用
    FTP服务:使用FileZilla搭建FTP服务
    FTP服务:ISS搭建服务
    javaweb项目使用RSA算法
    我在博客园的第一篇博客
    杰表打印跟乱码修改
    jsp页面角色判断
    test : 摘自 https://www.cnblogs.com/yyman001/p/3366764.html
    mybatis中sql查询不到数据单独运行sql可以获取数据
  • 原文地址:https://www.cnblogs.com/clarino/p/14372979.html
Copyright © 2011-2022 走看看