Java conversion from list to JSONL

Viewed 108

I'd like to convert a list of objects to JSONL where each object in the list will be a line in the json.

e:g: Let's say I have a list of Person and I want to convert that list to a separate file in the JSONL format

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

Convert List of person to 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}
2 Answers
import com.alibaba.fastjson.JSONArray;

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

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