简体   繁体   中英

How to convert TSV data to JSON Object in java

TSV Data: 在此处输入图像描述

Required OutPut :
[{
candidates: {
id:"agent_4",
text = "can i get a confirmation code",
count = 2},
{
id:"agent_11",
text = "text_2",
count =3},
}]

I got the similar question for JQ, but how can I achieve this in java? Convert TSV file to multiple JSON arrays with jq

Load file by BufferedReader and use JsonArray to format your Json output

    BufferedReader reader = new BufferedReader(new FileReader("data.tsv"));

    String[] fieldNames = reader.readLine().split("\t");

   
    List<JSONObject> rows = new ArrayList<>();

    // Read tsv file line by line
    String line;
    while ((line = reader.readLine()) != null) {
        
        String[] fields = line.split("\t");

        JSONObject row = new JSONObject();
        for (int i = 0; i < fieldNames.length; i++) {
            row.put(fieldNames[i], fields[i]);
        }
        rows.add(row);
    }

    reader.close();

    // Convert the list of rows to a JSON array
    JSONArray array = new JSONArray(rows);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM