1

I have a json

{
    "name":["A","B"],
    "class":"Science"
}

How can I convert it to List of Students (A,Science)(B,Science)

Students
{
    public String name;
    public String class;
}
Ujala Jha
  • 73
  • 6
  • Does this answer your question? [How to convert the following JSON String to POJO](https://stackoverflow.com/questions/41499935/how-to-convert-the-following-json-string-to-pojo) – Saif Ahmad Feb 02 '22 at 12:37
  • No, I have 1 Json object to be converted to List – Ujala Jha Feb 02 '22 at 12:41

1 Answers1

0

Since class is a Java keyword you can't create a variable with that name. Assuming you're using org.json for handling JSON.

Students{
     public String name;
     public String clazz; // variable name changed
}

Using the above Students class:

String req = "{\"name\":[\"A\",\"B\"],\"class\":\"Science\"}";

JSONObject jsonObject = new JSONObject(req);

JSONArray name = jsonObject.getJSONArray("name");
String aClass = jsonObject.getString("class");
List<Students> studentsList = new ArrayList<>();

for (int i = 0; i < name.length(); i++) {
    Students students = new Students();
    students.setName(name.getString(i));
    students.setClazz(aClass);
    studentsList.add(students);
}

System.out.println(studentsList);

OUTPUT:

[Students(A,Science), Students(B,Science)]
Saif Ahmad
  • 1,118
  • 1
  • 8
  • 24
  • yes, this seems to work. Is there any objectmapper or modelmapper support as well to do this? In case I have one more value in key - "class" in json, and I need permutation and combination of same to create List of students? (a,science)(b,science)(a,maths)(b,maths) – Ujala Jha Feb 02 '22 at 13:51
  • I don't think it'll be possible. – Saif Ahmad Feb 03 '22 at 04:11