How to convert Json Object to array of json objects

74 views Asked by At

Below is my input

nameJson : {"english":"tom","dutch":"john","spanish":"sam"}
sectionJson: {"english":"A","dutch":"B","spanish":"C"}

Below is my output should be look like

"students": [
{
        "name": "tom",
        "section": "A",
        "language":"english"
    
},
{
        "name": "john",
        "section": "B",
        "language":"dutch"
},
{
       "name": "sam",
        "section": "C",
        "language":"spanish"
}]

Please help me out in this. I have tried but I am not sure how to proceed.

JSONObject nameObj=new JSONObject(record[3]);
JSONObject sectionObj=new JSONObject(record[4]);
Map<String,Object> nameMap=new HashMap<>();
Map<String,Object> sectionMap=new HashMap<>();
nameMap= nameObj.toMap();
sectionMap= sectionObj.toMap();
1

There are 1 answers

0
Sakthi Prasad S On

To convert the given input into an array of JSON objects using the provided JSON objects nameJson and sectionJson, you can use the following Java code:

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonConversion {
    public static void main(String[] args) {
        String nameJsonStr = "{\"english\":\"tom\",\"dutch\":\"john\",\"spanish\":\"sam\"}";
        String sectionJsonStr = "{\"english\":\"A\",\"dutch\":\"B\",\"spanish\":\"C\"}";

        JSONObject nameJson = new JSONObject(nameJsonStr);
        JSONObject sectionJson = new JSONObject(sectionJsonStr);

        JSONArray studentsArray = new JSONArray();

        for (String language : nameJson.keySet()) {
            JSONObject studentObj = new JSONObject();
            studentObj.put("name", nameJson.getString(language));
            studentObj.put("section", sectionJson.getString(language));
            studentObj.put("language", language);
            studentsArray.put(studentObj);
        }

        JSONObject outputJson = new JSONObject();
        outputJson.put("students", studentsArray);

        System.out.println(outputJson.toString());
    }
}

OutPut:

{
  "students": [
    {
      "name": "tom",
      "section": "A",
      "language": "english"
    },
    {
      "name": "john",
      "section": "B",
      "language": "dutch"
    },
    {
      "name": "sam",
      "section": "C",
      "language": "spanish"
    }
  ]
}

This code parses the nameJson and sectionJson strings into JSONObject instances. Then, it iterates over the languages in nameJson, creates a JSONObject for each student, adds the corresponding values from nameJson, sectionJson, and the language itself, and finally adds each student object to the studentsArray. The resulting studentsArray is then added to the outputJson as the "students" property.

Please note that the code assumes you have the json.jar library (e.g., JSON-java) included in your project to handle JSON operations.