Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
Answer from Victor Dodon on Stack OverflowInstead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
There is an answer of your question: https://stackoverflow.com/a/17037364/1979882
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
json - How to put a List into a JSONObject and then read that object in Java? - Stack Overflow
How to parse json to get size of the list from jsonObject using Java?
java - JSON: Get list of JSON Objects - Stack Overflow
arrays - How to get a value which is a List from a JSONObject in Java - Stack Overflow
Videos
Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.
For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):
JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();
SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);
SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();
//if List not empty
if (!(sList.size() ==0)) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
Hi, All,
I am facing problem while parsing json tried different ways to parse json ending up with error. I actually want to get the size of list present in jsonObject so that I can run a for loop till that size and get attributes accordingly.
Running to the error - org.json.JSONException : A JSONArray text must start with '[' at 1 [character 2 line 1]
Json is present on the below link :
https://reqres.in/api/users?page=2
Can you guys please help me with different code snippet how can it be achieved? Will be very thankful to you all.
Your root JSON is an Array, so first create a JSONArray from your String.
Do this:
JSONArray arr = new JSONArray(jstring);
for (int i = 0; i < arr.length(); i++) { // Walk through the Array.
JSONObject obj = arr.getJSONObject(i);
JSONArray arr2 = obj.getJSONArray("fileName");
// Do whatever.
}
For more info, please refer to the docs on JSONArray and JSONObject.
You have to directly construct JSONArray from JSON string in this case.
JSONArray arr = new JSONArray(jstring);
you can get this data as a JsonArray
You can customize a little bit of code like it
public static void main(String[] args) throws ParseException {
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(
data);
JSONArray jasonArray = json.getJSONArray("data");
List list = new ArrayList();
int size = jasonArray.length();
int i = 0;
while (i < size) {
list.add(jasonArray.get(i));
i++;
}
System.out.println(list);
}
If anyone else is stuck here, It turned out I was on the right track, I can access the List using getJSONArray, but when iterating for each member, I use getString
public static Person parsePersonJson(String json) {
JSONObject currentPerson;
String name;
try {
currentPerson = new JSONObject(json);
// so I can access the name like
name = currentPerson.getString("name");
List<String> alsoKnownAs= new ArrayList<>();
//use getJSONArray to get the list
JSONArray arrayKnownAs = currentPerson.getJSONArray("alsoKnownAs");
for (int i = 0, l = arrayKnownAs.length(); i < l; i++) {
//This is where I was getting it wrong, i needed to use getString to access list items
alsoKnownAs.add(arrayKnownAs.getString(i));
}
Person thisPerson = new Person(
//I instantiate person object here
);
return thisPerson;
} catch (org.json.JSONException e) {
// error
}
return null;
}
Here a solution using com.fasterxml.jackson
Person.java:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
class Person {
final public String name;
final public List<String> alsoKnownAs;
@JsonCreator
public Person(
@JsonProperty("name") final String name,
@JsonProperty("alsoKnownAs") final List<String> alsoKnownAs
) {
this.name = name;
this.alsoKnownAs = alsoKnownAs;
}
public static Person parsePersonJson(String json) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readValue(json, Person.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Here a quick test:
PersonTest.java
import org.junit.Test;
public class PersonTest {
@Test
public void parseAJsonToAPerson() {
String json = "{\"name\":\"moses\",\"alsoKnownAs\":[\"njai\", \"njenga\",\"musa\"]}";
Person currentPerson = Person.parsePersonJson(json);
System.out.println("name: " + currentPerson.name);
System.out.println("alsoKnownAs: " + currentPerson.alsoKnownAs);
}
}
Test output is:
name: moses
alsoKnownAs: [njai, njenga, musa]
You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
For any one who looks for answer yet:
1.Add jackson-databind library to your build tools like Gradle or Maven
2.in your Code:
ObjectMapper mapper = new ObjectMapper();
List<Student> studentList = new ArrayList<>();
studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));