I have data like this:
NewsItem :
- id
- title
- date
- txt
There may be many NewsItems say 10. I have to send them to jquery.
I am doing this:
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0 ; i< list.size() ; i++){
p = list.get(i);
arr.put(p.getId());
arr.put(p.getTitle());
arr.put(new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()));
arr.put(getTrimmedText(p.getText()));
obj.put(""+i,arr);
arr = new JSONArray();
}
This will create a JSON string like this : {"1":["id","title","date","txt"],"2":[......and so on...
Is that correct way of doing this?
How can I parse this string so that I can get each news item object in jQuery so that I can access attr.
Like this:
obj.id,
obj.title
Or if this is wrong way of creating JSON string, please suggest some better way with example of parsing in jQuery.
I believe that you’re organizing your data backwards. It seems that you want to use an array of
NewsItems, and if so, then your java JSON generation code should look like this:Now your JSON string will look something like this:
Assuming that your NewsItem gettors return
Strings. The JSONObject methodputis overloaded to take primitive types also, so if, e.g. yourgetIdreturns anint, then it will be added as a bare JSONint. I’ll assume thatJSONObject.put(String, Object)callstoStringon the value, but I can’t verify this.Now in javascript, you can use such a string directly: