我相信您正在反向整理数据。似乎您想使用的数组
NewsItems,如果这样,则您的Java JSON生成代码应如下所示:
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();}现在,您的JSON字符串将如下所示:
[{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"}, {"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"}, ...]假设您的NewsItem获取者返回
Strings。JSONObject方法也
put被重载以采用原始类型,因此,例如,如果您
getId返回
int,则它将作为裸JSON添加
int。我假设
JSONObject.put(String,Object)调用
toString该值,但是我无法验证这一点。
现在,在javascript中,您可以直接使用这样的字符串:
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


