kotlin 从列表到JSONL的Java转换

wi3ka0sx  于 2023-10-23  发布在  Kotlin
关注(0)|答案(3)|浏览(139)

我想将一个对象列表转换为JSONL,其中列表中的每个对象都是JSON中的一行。
例如:假设我有一个Person列表,我想将该列表转换为JSONL格式的单独文件

List<Person> personList = Stream.of(
                new Person("John", "Peter", 34),
                new Person("Nick", "young", 75),
                new Person("Jones", "slater", 21 ),
                new Person("Mike", "hudson", 55))
                .collect(Collectors.toList());

将人员列表转换为JSONL

{"firstName" : "Mike","lastName" : "harvey","age" : 34}
{"firstName" : "Nick","lastName" : "young","age" : 75}
{"firstName" : "Jack","lastName" : "slater","age" : 21}
{"firstName" : "gary","lastName" : "hudson","age" : 55}
pjngdqdw

pjngdqdw1#

import com.alibaba.fastjson.JSONArray;

for (int i = 0; i < personList.size(); i++) {
    JSONObject obj = (JSONObject)array.get(i);
    System.out.println(obj.toJSONString());
}
5n0oy7gb

5n0oy7gb2#

import org.json.simple.JSONObject;

public static void main(String[] args) throws IOException {
        File fout = new File("output.jsonl");
        FileOutputStream fos = new FileOutputStream(fout);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
        for(int i=0;i<5;i++)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("source", "main()");
            jsonObject.put("path", "main.java");
            bw.write(jsonObject.toJSONString());
            bw.newLine();
    }
        bw.close();
    }
mcdcgff0

mcdcgff03#

您可以使用ndjson来生成JSONL。它使用jackson进行序列化和重命名

NdJsonObjectMapper ndJsonObjectMapper = new NdJsonObjectMapper();
    OutputStream out = ... ;
    Stream < Person> personStream = ...;
    ndJsonObjectMapper.writeValue(out, personStream);

免责声明:我开发ndjson是为了我个人使用。

相关问题