Java将列表转换为JSONL

3
我想将一个对象列表转换为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}
3个回答

1
import com.alibaba.fastjson.JSONArray;

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


2
你能添加一些有用的解释吗?看起来你更喜欢使用阿里巴巴的库,原因是abc等等。这将有助于更好地理解答案。欢迎来到SO! - supernova

1
你可以使用ndjson来生成JSONL。它使用jackson进行序列化和反序列化。
    NdJsonObjectMapper ndJsonObjectMapper = new NdJsonObjectMapper();
    OutputStream out = ... ;
    Stream < Person> personStream = ...;
    ndJsonObjectMapper.writeValue(out, personStream);

免责声明:我开发了ndjson仅供个人使用。

1
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();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接