zachThePerson zachThePerson - 6 months ago 32
Android Question

Android: How to parse JSON Array to string

The JSON file format I need to use looks like this

[{"fName":"Bob","lName":"Smoe","info":"is tall"},{"fName":"Claire","lName":"Smoegan","info":"has a big forehead"}]

I have an object list of people that I add to a JSON array. The code looks like this

for (int i = 0; i < peopleList.size(); i++){
try {
}catch (Exception e){

The problem is, I need to convert it to a string to write to a file, but when I use "jArray.toString()" it returns

"["com.example.zach.projectFile.Person@21b854e0", "com.example.zach.projectFile.Person@21b854e0", "com.example.zach.projectFile.Person@21b85400"....]

How do I get this to return it in the format requested above?


You are not following the rules for put() on a JSONArray. The parameter is supposed to be:

a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities. Unsupported values are not permitted and will cause the array to be in an inconsistent state.

com.example.zach.projectFile.Person is none of these. What JSONArray is doing is calling toString() on your Person objects and using that as the value for the array.

Your choices are:

  1. Implement something like toJSONObject() on Person, which returns a JSONObject representation of the Person (e.g., a JSONObject that, when turned into JSON, results in something like {"fName":"Bob","lName":"Smoe","info":"is tall"}). Then, use put(peopleList.get(i).toJSONObject() to fill in the JSONArray.

  2. Use something more sophisticated than the org.json classes, such as Gson.

Also, Andreas' note is correct. You are not parsing JSON. You are generating JSON. Parsing JSON would be converting a String containing JSON into Person objects.