Java中使用Fastjson將JSON檔案轉物件

阿壯Jonsson發表於2020-10-19

需要的依賴

我們這裡使用的是fastjson-1.2.73
Maven地址:https://mvnrepository.com/artifact/com.alibaba/fastjson

JSON檔案內容

[
  {
    "_index": "index-1",
    "_type": "type-1",
    "_id": "111111",
    "_score": 7.8561087,
    "_source": {
      "rooms": [
        "222222"
      ],
      "nickName": "333333"
    }
  },
  {
    "_index": "index-2",
    "_type": "type-2",
    "_id": "444444",
    "_score": 7.8561087,
    "_source": {
      "rooms": [
        "555555"
      ],
      "nickName": "666666"
    }
  }
]

程式碼

需求:取出_idroomsrooms中元素的個數nickName

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.FileInputStream;
import java.io.IOException;

public class JSONUtil {
    public static void main(String[] args) throws IOException {
        // 獲取檔案的輸入流物件
        FileInputStream fileInputStream = new FileInputStream("src/json3.json");
        int len;
        byte[] bytes = new byte[1024];
        StringBuilder stringBuffer = new StringBuilder();
        while ((len = fileInputStream.read(bytes)) != -1) {
            // 新增字串到緩衝區
            stringBuffer.append(new String(bytes, 0, len));
        }
        // 關閉資源
        fileInputStream.close();
        // 使用fastjson將字串轉換為JSON
        JSONArray jsonArray = JSONObject.parseArray(stringBuffer.toString());
        // 便利物件去除我們需要的資料
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
            String source = jsonObject.get("_source").toString();
            JSONObject jsonObject1 = JSONObject.parseObject(source);
            String rooms = jsonObject1.get("rooms").toString();
            JSONArray roomList = JSONArray.parseArray(rooms);
            String nickName = "";
            Object nickName1 = JSONObject.parseObject(source).get("nickName");
            if (nickName1 != null) {
                nickName = nickName1.toString();
            }
            // 將我們需要的資料輸出到控制檯
            System.out.println(jsonObject.get("_id") + " \t" + nickName + "\t" + roomList.size() + "\t" + rooms);
        }
    }
}

效果

在這裡插入圖片描述

相關文章