creating json string using JSONObject and JSONArray - java

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:
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

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
}

For converting JSON object to JSON string use
JSON.stringify(json_object)
For reverse use:
JSON.parse(json_string)

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"]

Related

Need some assistance trying to parse this JSON response from our backend server

Currently working on an android app and I need help on how I can go about extracting the subfields within the responses field of this json object:
Currently I am doing the following to extract some of the other fields:
JSONObject json = new JSONObject(response2);
int id = json.getInt("id");
String desc = json.getString("description");
JSONObject json2 = json.getJSONObject("owner");
String username = json2.getString("userName");
You need to create logic to parse the data. Every item from the JSON string is in the JSONObject you created with
JSONObject json = new JSONObject(response2);
You're on the right track with what you're doing. Just use the corresponding methods available in JSONObject and JSONArray classes to move through the object.
Start with the main object
{ // <-- this is your main object (AKA JSONObject json = new JSONObject(response2))
"id": 1, // to pull this id use json.getInt("id");
"title": "some text here", // to pull this title use json.getString("title");
...
"owner": { // Here's the logic part, owner is itself, a JSON object. so now you must extract it and parse through it.
// to pull the "owner" JSON object, use JSONObject ownerObject = json.getJSONObject("owner");
"userId": 1, // Now use the ownerObject to pull it's values. ownerObject.getInt("userId");
"userName": "TestingUser", // to pull this userName use ownerObject.getString("userName");
...
}
...
}
If it's an array, for example:
"someJSONArray": [{ "id": 1, "userName": "TestingUser1" }, { "id": 2, "userName": "TestingUser2" }]
then you would call:
JSONArray someJSONArray = getJSONArray("someJSONArray");
// Get each object from the array.
JSONObject object1 = someJSONArray.getJSONObject(0);
JSONObject object2 = someJSONArray.getJSONObject(1);
or if the array contains a string, for example:
"someKey": [ 23, 435, 123, 6345, 123 ]
then you would call:
JSONArray someKeyArray = getJSONArray("someKey");
for (int i = 0; i < someKeyArray.length(); i++) {
// Extract the value.
int itemValue = someKeyArray.getInt(i);
}
The data is there, you just have to parse it.

How to get data from JSONobject and display it into a listview?

This is my JSON
{
"data": [
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
}
]
}
]
}
Now I am trying to display it into a listView how would I do that this is what i have right now (for testing purposes i am just trying to display all the names in a toast)
JSONObject jsonObj = new JSONObject(jsonStr);
int length = jsonObj .length();
for(int i=0; i<length; i++) {
Toast.makeText(this, jsonObj.getJSONArray("data").
getJSONObject(i).getString("Name"), Toast.LENGTH_LONG).show();
}
The Above code only display one name and not multiple names. How can I make it for multiple names?
Take a look this code snippet
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name").toString(), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
// getting json objects from Ingredients json array
for(int j=0; j<len; j++)
{
JSONObject json = ja.getJSONObject(j);
Toast.makeText(this, json.getString("name").toString(), Toast.LENGTH_LONG).show();
}
}
I recommend to use 'Log' instead using 'Toast'.
If any confusion or query let me know, i will try my best to resolve it.
If answer is satisfiable please mark it as correct answer.
Happy coding!
Thanks
You are getting the length of JSONObject, but you should get the length of JSONArray inside that JSONObject in order to iterate though json array items.
int length = jsonObj.getJSONArray("data").size()
I think you are guessing it wrong. Look closely you have a Json in that you have array which is JsonArray with the name/key "data"
then in that you can get it and traverse it index by index. For you I am providing you a road map so that things make easy for you conceptually
Make a model class which may able to store the values as you are getting in response of your api or in this json respone.
Take an array of type of your model class to store values
Now you can add for loop to save values or you can parse and save your jason array into your array you made to handle the jasonarray
this is easily be understand by this link and this is a working example to parse the json array and to show in your list view. You have nothing to worry about after reading these two links.
get your result from URL where your json is and store to any variable (result here) , then decode it i am showing below,
try this , it may give you some hint , i have not tried but may help you
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.optJSONArray("data");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
int id = jsonObjects.optInt("id");
String varMessage = jsonObjects.optString("varMessage");
String Image = jsonObjects.optString("Image");
String Category = jsonObjects.optString("Category");
String Method = jsonObjects.optString("Method");
JSONArray jsonArrayIngredients = jsonObject.optJSONArray("Ingredients");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String name = jsonObjects.optString("name");
}
}
}

parse JSON to grab 'name' from an array

I'm trying to grab the 'name' from the JSON snippet I've included. I have tried the following but what I'm expecting is never grabbed.
Edit: 'output' is the full JSON string in case it wasn't already understood ;)
JSONObject result = null;
JSONArray data = null;
try {
try {result = new JSONObject(output);} catch (JSONException e) {e.printStackTrace();}
try {
data = result.getJSONArray("data");
for(int a=0;a<data.length();a++){
System.out.println(result.getJSONObject(String.valueOf(a)).getString("name"));//getJSONObject("results")
}
Here is the JSON snippet I'm trying to work with:
{
"code": 200,
"status": "Ok",
"copyright": "© 2015 MARVEL",
"attributionText": "Data provided by Marvel. © 2015 MARVEL",
"attributionHTML": "Data provided by Marvel. © 2015 MARVEL",
"etag": "b130a8b7af591e4e7ca078753f9c5c8a76e55e5d",
"data": {
"offset": 0,
"limit": 20,
"total": 1485,
"count": 20,
"results": [
{
"id": 1011334,
"name": "3-D Man",
"description": "",
"modified": "2014
.
.
.
.
.
.
.
.
.
.
To get you started, "data" points to a JSON Object, not array. So it should be:
data = result.getJSONObject("data");
Then, "results" points to a JSON array:
JSONArray results = data.getJSONArray("results");
Then you can try your loop. You shouldn't be turning a into a String - getJSONObject() takes an int for the index.
In case you're confused between Objects and Arrays, a JSON object has key - value pairs and are enclosed in curly braces. The keys are strings and the values can be a mix of any type:
{"key1": 5, "key2": "value2", "key3": {
"anotherObject": [1,2,3,4]
}
}
An array is a list of objects and is enclosed in square brackets:
[{...}, {...}, {...}]
The elements in the list don't have to be JSON objects, and in good JSON they will all be of the same type:
[1,2,3,4,4] or ["we", "are", "in", "an", "array"]
JSONTokener jsonTokener = new JSONTokener(jsonVaule);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
Int code =jsonObject.getInt("code");
String status =jsonObject.getString("status");
//{obejcet,obejcet,...}
for data{} is the same way~
JSONObject dataJsObject = (JSONObject) jsonObject.getJsonObject("data");
int offset =dataJsObject.getInt(""iffset);
....
//[{},{}] this type is jsonArrary
JSONArray results = dataJsObject.getJSONArray("results");
for(JSONObject resultJsonObj:JSONArray){
Int id =jsonObject.getInt("id");
//...and so on
}
hope it can help you~
You can parse like that
JsonObject obj = new JsonObject(StringResponse);
String code = obj.getString(code);
//same way you can get other string
JsonObject obj1 = obj.getJsonObject(Data);
String offset= obj.getString(offset);
//same way you can get other string
JsonArray jsonarr = obj1.getJsonArray(results);
for(i=0;i< jsonarr.size(); i++){
JsonObject innerObj = jsorr.getJsonObject(i);
String id= obj.getString(id);
//same way you can get other string
}
Hope It will helpful for you

Reading JSON file using json-smart

I am trying to read the values from a JSON file to array for further processing. I am using JSON-Smart 1.2.0 library for the same. Due to some restrictions, I can not use the 2.0 version.
I am getting the following exception.
java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to net.minidev.json.JSONObject
I am even tried using JSONArray instead of JSONObject. What I am doing wrong over here? Is this correct way to read json content?
Below is the java code.
JSONObject json = (JSONObject) JSONValue.parseWithException(browsers);
JSONArray array = (JSONArray) json.get("friends");
for (int i = 0; i < array.size(); i++) {
JSONObject cap = (JSONObject) array.get(i);
String first = (String) cap.get("name");
System.out.println(first);
}
Below is the json file content.
[
{
"friends": [
{
"id": 0,
"name": "test1"
},
{
"id": 1,
"name": "test2"
}
]
}
]
Your JSON contains an array which has one single object element so you should parse it like that:
JSONArray root = (JSONArray) JSONValue.parseWithException(json);
JSONObject rootObj = (JSONObject) root.get(0);
JSONArray array = (JSONArray) rootObj.get("friends");
for (int i = 0; i < array.size(); i++) {
JSONObject cap = (JSONObject) array.get(i);
String first = (String) cap.get("name");
System.out.println(first);
}
If it can have more elements add a for loop instead of root.get(0).

Android - How to parse JSONObject and JSONArrays from api.rottentomatoes

so, there's this JSON code. Im trying to get the "abridged_cast".
but its complicated.
its JSONObject
inside JSONArray onside jSONObject Inside JsonArray....
{
"total": 591,
"movies": [
{
"title": "Jack and Jill",
"year": 2011,
"runtime": "",
"release_dates": {
"theater": "2011-11-11"
},
"ratings": {
"critics_score": -1,
"audience_score": 90
},
"synopsis": "",
"posters": {
"thumbnail": "",
"profile": "",
"detailed": "",
"original": ""
},
"abridged_cast": [
{
"name": "Al Pacino",
"characters": []
},
{
"name": "Adam Sandler",
"characters": []
},
{
"name": "Katie Holmes",
"characters": []
}
],
"links": {
"self": "",
"alternate": ""
}
}
],
"links": {
"self": "",
"next": ""
},
"link_template": ""
}
this is my code for getting "title" and "year"
if (response != null) {
try {
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray movies = jsonResponse.getJSONArray("movies");
// add each movie's title to an array
movieTitles = new String[movies.length()];
for (int i = 0; i < movies.length(); i++) {
JSONObject movie = movies.getJSONObject(i);
movieTitles[i] = movie.getString("title");
}
hope someone would help me because i cant figure out how to get the abridged_cast"
movies contains an array of "movie" objects. Each one of those objects contains a field abridged_cast that is an array of (let's call them "cast member") objects.
If you're not going to map to a POJO and instead are going through the JSON, you simply need to get that array in your loop after getting movie, and get each "cast member" object from that array in the same manner using another loop.
...
JSONArray cast = movie.getJSONArray("abridged_cast");
for (int j = 0; j < cast.length(); j++) {
JSONObject castMember = cast.getJSONObject(j);
...
}
Edit from comments: Your original question involved how to extract the information from the JSON you have; the above code explains that. It now seems like you're asking a more fundamental programming question around how to use it.
If you're going to use the included org.json classes that come with Android, you now know how to access the information in the returned JSON object. And you could write methods around the parsed JSONObject to access the data as-is using the objects and methods from the json.org package. For example, you could write a "getMovie()" method that took the name of the movie as a string and searched that "movies" array for the right one and returned it as a JSONObject.
Normally you would create classes in Java that encapsulate the data returned in that JSON and use data structures that lend themselves to your access patterns (For example, a Map that conatained all the movies using their names as keys). Using the org.json classes you'll have to instantiate those objects and populate them manually as you parse the JSON like you're doing in your question. If you used either the Gson or Jackson JSON parsing libraries they are capable of taking the JSON you have and mapping all the data to the classes your create and returning them in a single call.
try {
String Movie = null;
String abridged = null;
JSONArray jsonResponse = new JSONArray(response);
for (int i = 0; i< jsonResponse.length(); i++) {
Movie = jsonResponse.getJSONObject(i).getString("movies").toString();
System.out.println("movies="+Movie);
abridged = jsonResponse.getJSONObject(i).getString("abridged_cast").toString();
}
JSONArray jArray = new JSONArray(Movie);
for (int i = 0; i< jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title").toString();
System.out.println("title="+title);
}
JSONArray jabridgeArray = new JSONArray(abridged);
for (int i = 0; i< jabridgeArray.length(); i++) {
String title = jabridgeArray.getJSONObject(i).getString("name").toString();
System.out.println("title="+title);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources