8

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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
JAVAGeek
  • 2,674
  • 8
  • 32
  • 52

4 Answers4

22

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
pb2q
  • 58,613
  • 19
  • 146
  • 147
  • how can i traverse each object in a loop.... arr[0] .. arr[1] would be ok but if i don't know number of items then how can i access them ??? – JAVAGeek Jul 20 '12 at 21:29
  • @JAVAGeek: javascript arrays have a `length` property, see edit – pb2q Jul 20 '12 at 21:32
  • 1
    what library is used? javax.json? – 200ok Jul 03 '15 at 12:11
  • @pb2q you might want to change `arr.put(obj);` to `arr.add(obj);` to avoid `The method put(JSONObject) is undefined for the type JSONArray` error. – Mad-D Sep 27 '17 at 20:46
1

The idea of the json object is the same as a dictionary/map where you have keys and values assigned to those keys, so what you want to construct would be something like this:

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

where the "1" is the id and the contents is another dictionary/map with the info.

lets say you assigned the object to a variable named my_map, now you will be able to handle it as:

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

to iterate over it just use:

for (info in my_map){
    data = my_map[info];
    //do what you need
}
Hassek
  • 8,715
  • 6
  • 47
  • 59
0

For converting JSON object to JSON string use

JSON.stringify(json_object)

For reverse use:

JSON.parse(json_string)
Paritosh Singh
  • 6,288
  • 5
  • 37
  • 56
0

This is the correct way -

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);
}

This will generate

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

Now, when you parse the json at client end, you can iterate over the array and for each json object you can access as -

obj.id or obj["id"]

devang
  • 5,376
  • 7
  • 34
  • 49