最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

復(fù)雜JSON字符串轉(zhuǎn)換為Java嵌套對象的實現(xiàn)

 更新時間:2021年09月17日 15:10:48   作者:琴水玉  
這篇文章主要介紹了復(fù)雜JSON字符串轉(zhuǎn)換為Java嵌套對象的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

背景

實際開發(fā)中,常常需要將比較復(fù)雜的 JSON 字符串轉(zhuǎn)換為對應(yīng)的 Java 對象。這里記錄下解決方案。

如下所示,是入侵事件檢測得到的 JSON 串:

[{"rule_id":"反彈shell","format_output":"進程 pname 反向連接到 %dest_ip%:%dest_port%","info":{"process_events":{"pid":21,"pname":"nginx","cmdline":"curl www.cfda.com","ppid":7,"ppname":"bash"},"proc_trees":[{"pid":21,"pname":"nginx","cmdline":"curl www.cfda.com","ppid":7,"ppname":"bash"}],"containers":{"container_id":"fef4636d8403871c2e56e06e51d609554564adbbf8284dd914a0f61130558bdf","container_name":"nginx","image_id":"4eb8f7c43909449dbad801c50d9dccc7dc86631e54f28b1a4b13575729065be8","status":"Running"},"sockets":{"src_ip":"127.0.0.1","src_port":"8080","type":"1","in_out":"0","dest_ip":"localhost","dest_port":"80"}}}]

方法

預(yù)備工作

把上述 json 串放在 src/test/resources 下,寫一個文件讀寫程序來解析。 其實放在哪里不重要,重要的是拿到這個 JSON 串便于后續(xù)解析。

public static String readFromSource(String filename) {
    try {
      InputStream is = RWTool.class.getResourceAsStream(filename);
      byte[] bytes = new byte[4096];
      int num = 0;
      String json = "";
      while((num=is.read(bytes))>0){
        json=new String(bytes,0,num);
      }
      return json;
    } catch (Exception ex) {
      throw new RuntimeException(ex.getCause());
    }
}

構(gòu)建對象模型

首先,要根據(jù)這個 JSON 字符串解析出對應(yīng)的數(shù)據(jù)模型 AgentDetectEventData。主要就是按照 JSON 串中的 key 的層次結(jié)構(gòu)來建立。

@Getter
@Setter
public class AgentDetectEventData {
    @SerializedName("rule_id")
    @JsonProperty("rule_id")
    private String ruleId;
    @SerializedName("format_output")
    @JsonProperty("format_output")
    private String formatOutput;
    @SerializedName("info")
    @JsonProperty("info")
    private AgentDetectEventDetail info;
}
@Getter
@Setter
public class AgentDetectEventDetail {
    @SerializedName("process_events")
    @JsonProperty("process_events")
    private ProcessEvent processEvent;
    @SerializedName("proc_trees")
    @JsonProperty("proc_trees")
    private List<ProcessTree> procTree;
    @SerializedName("containers")
    @JsonProperty("containers")
    private Container container;
    @SerializedName("sockets")
    @JsonProperty("sockets")
    private Socket socket;
}
@Getter
@Setter
public class ProcessEvent {
    @SerializedName("pid")
    @JsonProperty("pid")
    private String pid;
    @SerializedName("pname")
    @JsonProperty("pname")
    private String pname;
    @SerializedName("cmdline")
    @JsonProperty("cmdline")
    private String cmdline;
    @SerializedName("ppid")
    @JsonProperty("ppid")
    private String ppid;
    @SerializedName("ppname")
    @JsonProperty("ppname")
    private String ppname;
}
@Getter
@Setter
public class ProcessTree {
    @SerializedName("pid")
    @JsonProperty("pid")
    private String pid;
    @SerializedName("pname")
    @JsonProperty("pname")
    private String pname;
    @SerializedName("cmdline")
    @JsonProperty("cmdline")
    private String cmdline;
    @SerializedName("ppid")
    @JsonProperty("ppid")
    private String ppid;
    @SerializedName("ppname")
    @JsonProperty("ppname")
    private String ppname;
}
@Getter
@Setter
public class Container {
    @SerializedName("container_id")
    @JsonProperty("container_id")
    private String containerId;
    @SerializedName("container_name")
    @JsonProperty("container_name")
    private String containerName;
    @SerializedName("image_id")
    @JsonProperty("image_id")
    private String imageId;
    @SerializedName("status")
    @JsonProperty("status")
    private String status;
}
@Getter
@Setter
public class Socket {
    @SerializedName("src_ip")
    @JsonProperty("src_ip")
    private String srcIp;
    @SerializedName("src_port")
    @JsonProperty("src_port")
    private String srcPort;
    @SerializedName("type")
    @JsonProperty("type")
    private String type;
    @SerializedName("in_out")
    @JsonProperty("in_out")
    private String inOut;
    @SerializedName("dest_ip")
    @JsonProperty("dest_ip")
    private String destIp;
    @SerializedName("dest_port")
    @JsonProperty("dest_port")
    private String destPort;
}

這里有兩個注意點:

  • JSON 字符串的字段命名是下劃線形式,而 Java 對象的屬性命名是駝峰式的,這里需要做一個字段名映射轉(zhuǎn)換。 使用 Jackson 庫來轉(zhuǎn)換,是 @JsonProperty 注解; 使用 gson 庫來轉(zhuǎn)換,是 @SerializedName 注解。
  • 需要加 getter / setter 方法。

對象模型建立后,就成功了一大半。接下來,就是使用 json 庫來解析了。

使用jackson 庫解析

public class JsonUtil {
  private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
  private static final ObjectMapper MAPPER = new ObjectMapper();
  static {
    // 為保持對象版本兼容性,忽略未知的屬性
    MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // 序列化的時候,跳過null值
    MAPPER.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    // date類型轉(zhuǎn)化
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    MAPPER.setDateFormat(fmt);
  }
  /**
   * 將一個json字符串解碼為java對象
   *
   * 注意:如果傳入的字符串為null,那么返回的對象也為null
   *
   * @param json json字符串
   * @param cls  對象類型
   * @return 解析后的java對象
   * @throws RuntimeException 若解析json過程中發(fā)生了異常
   */
  public static <T> T toObject(String json, Class<T> cls) {
    if (json == null) {
      return null;
    }
    try {
      return MAPPER.readValue(json, cls);
    } catch (Exception e) {
      throw new RuntimeException(e.getCause());
    }
  }
  public static <T> String objectToJson(T obj){
    if(obj == null){
      return null;
    }
    try {
      return obj instanceof String ? (String) obj : MAPPER.writeValueAsString(obj);
    } catch (Exception e) {
      return null;
    }
  }
  public static <T> T jsonToObject(String src, TypeReference<T> typeReference){
    if(StringUtils.isEmpty(src) || typeReference == null){
      return null;
    }
    try {
      return (T)(typeReference.getType().equals(String.class) ? src : MAPPER.readValue(src, typeReference));
    } catch (Exception e) {
      logger.warn("Parse Json to Object error",e);
      throw new RuntimeException(e.getCause());
    }
  }
  public static <T> T jsonToObject(String src, Class<?> collectionClass,Class<?>... elementClasses){
    JavaType javaType = MAPPER.getTypeFactory().constructParametricType(collectionClass,elementClasses);
    try {
      return MAPPER.readValue(src, javaType);
    } catch (Exception e) {
      logger.warn("Parse Json to Object error",e);
      throw new RuntimeException(e.getCause());
    }
  }
}

單測:

public class JsonUtilTest {
    @Test
    public void testParseJson() {
        String json = RWTool.readFromSource("/json.txt");
        List<AgentDetectEventData> ade = JsonUtil.jsonToObject(json, new TypeReference<List<AgentDetectEventData>>() {});
        Assert.assertNotNull(ade);
    }
    @Test
    public void testParseJson2() {
        String json = RWTool.readFromSource("/json.txt");
        List<AgentDetectEventData> ade = JsonUtil.jsonToObject(json, List.class, AgentDetectEventData.class);
        Assert.assertNotNull(ade);
    }
}

引入POM依賴為:

<dependency>
       <groupId>org.codehaus.jackson</groupId>
       <artifactId>jackson-mapper-asl</artifactId>
       <version>1.9.4</version>
</dependency>

使用GSON解析

public class GsonUtil {
  static GsonBuilder gsonBuilder = null;
  static {
    gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
  }
  public static Gson getGson() {
    return gsonBuilder.create();
  }
  public static <T> T fromJson(String json, Class<T> cls) {
    return getGson().fromJson(json, cls);
  }
  public static <T> T fromJson(String json, Type type) {
    return getGson().fromJson(json, type);
  }
}

單測:

public class GsonUtilTest {
    @Test
    public void testParseJson() {
        String json = RWTool.readFromSource("/json.txt");
        List<AgentDetectEventData> ade = GsonUtil.fromJson(json, new TypeToken<List<AgentDetectEventData>>(){}.getType());
        Assert.assertNotNull(ade);
    }
}

引入 POM 為:

<dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.3.1</version>
</dependency>

不含列表的嵌套對象

如果是不含列表的嵌套對象,則使用帶 Class cls 入?yún)⒌姆椒ǎ?/p>

@Test
public void testParseSimpleNestedJson() {
    String json = "{\"goods\":{\"desc\":\"2箱*250g\",\"goodsId\":8866,\"orderNo\":\"E20210522120237009258\",\"shopId\":659494,\"title\":\"認養(yǎng)一頭牛\"},\"order\":{\"bookTime\":1621656157,\"codPay\":false,\"deliveryType\":\"express\",\"orderNo\":\"E20210522120237009258\",\"shopId\":659494,\"userId\":1476}}";
    BookInfo bookInfo = JsonUtil.toObject(json, BookInfo.class);
    Assert.assertNotNull(bookInfo);
}
@Test
public void testParseSimpleNestedJson() {
    String json = "{\"goods\":{\"desc\":\"2箱*250g\",\"goodsId\":8866,\"orderNo\":\"E20210522120237009258\",\"shopId\":659494,\"title\":\"認養(yǎng)一頭牛\"},\"order\":{\"bookTime\":1621656157,\"codPay\":false,\"deliveryType\":\"express\",\"orderNo\":\"E20210522120237009258\",\"shopId\":659494,\"userId\":1476}}";
    BookInfo bookInfo = GsonUtil.fromJson(json, BookInfo.class);
    Assert.assertNotNull(bookInfo);
}

讀者可以自行解析出 BookInfo 的對象模型。

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 零基礎(chǔ)寫Java知乎爬蟲之抓取知乎答案

    零基礎(chǔ)寫Java知乎爬蟲之抓取知乎答案

    上篇文章我們已經(jīng)能把知乎的問題抓出來了,但是答案還木有抓出來。這一回合,我們就連著把答案也一起從網(wǎng)站中摳出來=。=
    2014-11-11
  • Maven優(yōu)雅的添加第三方Jar包的方法

    Maven優(yōu)雅的添加第三方Jar包的方法

    下面小編就為大家?guī)硪黄狹aven優(yōu)雅的添加第三方Jar包的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • 淺談Java中FastJson的使用

    淺談Java中FastJson的使用

    今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識,文章圍繞著FastJson的使用展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • ElasticSearch學(xué)習(xí)之文檔API相關(guān)操作

    ElasticSearch學(xué)習(xí)之文檔API相關(guān)操作

    這篇文章主要為大家介紹了ElasticSearch學(xué)習(xí)之文檔API相關(guān)操作,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-01-01
  • JAVA拋出異常的三種形式詳解

    JAVA拋出異常的三種形式詳解

    這篇文章主要介紹了JAVA拋出異常的三種形式詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • POST方法給@RequestBody傳參數(shù)失敗的解決及原因分析

    POST方法給@RequestBody傳參數(shù)失敗的解決及原因分析

    這篇文章主要介紹了POST方法給@RequestBody傳參數(shù)失敗的解決及原因分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • idea類名顯示多行的設(shè)置方式

    idea類名顯示多行的設(shè)置方式

    在IntelliJ IDEA中,類名的顯示方式可以通過設(shè)置來調(diào)整,若想設(shè)置為單行顯示,需在設(shè)置中找到相關(guān)選項并勾選“√”,若需多行顯示,則取消勾選即可,此操作有助于優(yōu)化代碼視圖,提升開發(fā)效率
    2024-09-09
  • SpringAOP中的通知Advice詳解

    SpringAOP中的通知Advice詳解

    這篇文章主要介紹了SpringAOP中的通知Advice詳解,Spring 的 AOP 功能中一個關(guān)鍵概念是通知Advice與切點Pointcut表達式相關(guān)聯(lián)在特定節(jié)點織入一些邏輯,Spring 提供了五種類型的通知,需要的朋友可以參考下
    2023-08-08
  • 詳解rabbitmq創(chuàng)建queue時arguments參數(shù)注釋

    詳解rabbitmq創(chuàng)建queue時arguments參數(shù)注釋

    這篇文章主要介紹了rabbitmq創(chuàng)建queue時arguments參數(shù)注釋,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • Java多線程中的CountDownLatch解析

    Java多線程中的CountDownLatch解析

    這篇文章主要介紹了Java多線程中的CountDownLatch解析,CountDownLatch是一個阻塞部分線程直到其他線程執(zhí)行完成后喚醒的同步計數(shù)器,核心是其內(nèi)部類Sync繼承于AQS,同時也是利用的AQS的同步原理,也稱之為閉鎖,需要的朋友可以參考下
    2023-11-11

最新評論

云梦县| 塔河县| 东光县| 杨浦区| 藁城市| 江陵县| 杂多县| 武清区| 沙洋县| 额尔古纳市| 三明市| 南雄市| 牟定县| 和静县| 遂昌县| 东阿县| 东源县| 贞丰县| 晴隆县| 福贡县| 曲靖市| 乐至县| 枝江市| 织金县| 湖南省| 浪卡子县| 襄垣县| 梁河县| 启东市| 郧西县| 昌邑市| 廊坊市| 徐汇区| 衡水市| 大庆市| 武邑县| 拉萨市| 鄱阳县| 桐梓县| 郑州市| 淳化县|