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:
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0 ; i< list.size() ; i++)
{
p = list.get(i);
obj.put("id", p.getId());
obj.put("title", p.getTitle());
obj.put("date". new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()));
obj.put("txt", getTrimmedText(p.getText()));
arr.put(obj);
obj = new JSONObject();
}
Now your JSON string will look something like this:
[{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"},
{"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"},
...]
Assuming that your NewsItem gettors return Strings
. The JSONObject method put
is overloaded to take primitive types also, so if, e.g. your getId
returns an int
, then it will be added as a bare JSON int
. I'll assume that JSONObject.put(String, Object)
calls toString
on the value, but I can't verify this.
Now in javascript, you can use such a string directly:
var arr =
[{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"},
{"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"}];
for (i = 0; i < arr.length; i++)
alert(arr[i].title); // should show you an alert box with each first title
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…