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 {
jArray.put(peopleList.get(i));
}catch (Exception e){
e.printStackTrace();
}
}
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?
1 Answer 1
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:
Implement something like
toJSONObject()onPerson, which returns aJSONObjectrepresentation of thePerson(e.g., aJSONObjectthat, when turned into JSON, results in something like{"fName":"Bob","lName":"Smoe","info":"is tall"}). Then, useput(peopleList.get(i).toJSONObject()to fill in theJSONArray.Use something more sophisticated than the
org.jsonclasses, 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.
3 Comments
JSONObject instances per Person. It sounds like you are reusing the same one.
jArrayis.