2

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 Answers2

0
import com.alibaba.fastjson.JSONArray;

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

supernova
  • 1,762
  • 1
  • 14
  • 31
  • 2
    Could you add some useful explanation? Looks like you prefer using an alibaba lib for reason abc and so forth. This will help understanding the answer better. And welcome to SO! – supernova Dec 21 '21 at 16:24
0
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();
    }
Lokeshwar G
  • 136
  • 6