I’m moving away from Serializable objects (need to cache and move things around – everybody seems to say to stay away from Serializable objects) and beginning write methods to transform my complex objects into JSONObjects.
The point: I’ve beginning to play around with how to create JSONObjects from my complex objects. I naively just tried this:
JSONObject toReturn = new JSONObject();
Iterator<LocationModel> locIter = locationList.iterator();
while (locIter.hasNext())
{
try {
toReturn.put("location", locIter.next());
} catch (JSONException e) {
}
}
where LocationModel looks like this:
public class LocationModel implements Serializable {
private String name;
private double Longitude;
private double Latitude;
private String description;
public LocationModel(
basic construtor sets variables above
}
public String toString()
{
return (name + " 8888 " + longitude + "/" + latitude + " !! " + description);
}
}
Now the strange thing (to me atleast) is the fact that after the Iterator in the first chunk of code is complete, I output the JSONObject as a string and I see it looks like:
{“location”:”LocationName 8888 -1/1 !! some description here”}
QUESTIONS
- In the docs for JSONObject there is no mention of JSONObject.put(name,Object) calling the Objects “toString” function so how/why does it do that? In reality my LocationModel class has other functions that return Strings so it isn’t the only function that returns a string.
I would strongly recommend you to use gson for a start, and if you need the extra speed of some of the other json parsers you could replace gson later on. Have used it for several large projects and its just takes days of a project 🙂
https://sites.google.com/site/gson/gson-user-guide
Gson is a lib for decoding and encoding java objects to json. Its quite light weight but not the fastest out there, it is however the fastest to integrate with, literally oneliners for both encode and decode of a object, no matter how big and complex the object might be, as long as you have the domain objects for the data your working with.