Reputation: 61
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());
{"firstName" : "Mike","lastName" : "harvey","age" : 34}
{"firstName" : "Nick","lastName" : "young","age" : 75}
{"firstName" : "Jack","lastName" : "slater","age" : 21}
{"firstName" : "gary","lastName" : "hudson","age" : 55}
Upvotes: 3
Views: 1212
Reputation: 348
You can use ndjson for generating JSONL. It uses jackson for serialization and deserialization
NdJsonObjectMapper ndJsonObjectMapper = new NdJsonObjectMapper();
OutputStream out = ... ;
Stream < Person> personStream = ...;
ndJsonObjectMapper.writeValue(out, personStream);
Disclaimer: I developed ndjson for my personal use.
Upvotes: 1
Reputation: 146
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();
}
Upvotes: 1
Reputation: 11
import com.alibaba.fastjson.JSONArray;
for (int i = 0; i < personList.size(); i++) {
JSONObject obj = (JSONObject)array.get(i);
System.out.println(obj.toJSONString());
}
Upvotes: 1