Java中使用Fastjson将JSON文件转对象

需要的依赖

我们这里使用的是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);
        }
    }
}

效果

在这里插入图片描述

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页