Creating a json string using JSONObject and JSONArray

I have the following data:

NewsItem:

  • ID
  • title
  • the date
  • Txt

There may be many NewsItems to say 10. I have to post them in jquery.

I'm doing it:

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 as follows: {"1":["id","title","date","txt"],"2":[......and so on...

Is this the right way to do this?

How can I parse this line so that I can get every news item object in jQuery so that I can access attr.

Like this:

obj.id,
obj.title

Or, if this is the wrong way to create a JSON string, please suggest a better way with jQuery parsing example.

+5
source share
4 answers

, . , 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"},
 ...]

, gettors 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
+14

json- , /, , , , , :

{"1": {"title": "my title", "date": "17-12-2011", "text": "HELLO!"}, "2": ....}

"1" - , - / .

my_map, :

 my_map.1.title
 my_map.3.text
 ...

, :

for (info in my_map){
    data = my_map[info];
    //do what you need
}
+1

JSON JSON

JSON.stringify(json_object)

:

JSON.parse(json_string)
0

-

final JSONArray arr = new JSONArray();

for(int i = 0 ; i< list.size() ; i++) {
    final JSONObject obj = new JSONObject();
    p = list.get(i);
    obj.add("id", p.getId());
    obj.add("title", p.getTitle());
    obj.add("date", new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()));
    obj.add("txt", getTrimmedText(p.getText()));
    arr.add(obj);
}

[{"id": 1, "date": 222, "title": "abc", "txt": "some text"}, {...}]

, json , json, , -

obj.id obj["id"]

0

All Articles