Managment of JSON objects and JSON arrays - java

I'm new with JSON and my question might be not very hard, but I can not find the way to deal with my purpose.
I'm trying to develop the code so that I can manage some JSON content. In my case the JSON info is:
{"posts":[{"id":1a00b,"name":"Michael Thomson","info":"he is crazy"},
{"id":18,"name":"Jason Williams","info":"he is tall"}]}
Now, I'd like to get the strings from each JSON object (using Java). That's the code I have developed:
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONArray jsonArray = jsonResult.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject childJSONObject = jsonArray.getJSONObject(i);
String id = childJSONObject.getString("id");
String name = childJSONObject.getString("name");
String info = childJSONObject.getString("info");
}
The error seems to be related with the sentence:
JSONArray jsonArray = jsonResult.getJSONArray("posts");
The method getJSONArray(String) is undefined for the type String
Those are the libraries I'm using to deal with
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
Thank you very much in advance!

jsonResult is a String. You need to turn it into a JSONObject first.
JSONObject obj = new JSONObject(jsonResult);
JSONArray jsonArray = obj.getJSONArray("posts");

Related

How change type of JSONObject when using javax

I have a StringBuilder:
My code is the following:
String response = sb.toString();
// logger.info("response is '{}' ", response);
JsonObject jsonObject = new JsonObject(response);
JsonObject fileStatuses = jsonObject.getJsonObject("FileStatuses");
JsonArray fileStatus = (JsonArray) fileStatuses.getJsonArray("FileStatus");
for (int i = 0; i < fileStatus.size(); ++i) {
JsonObject rec = fileStatus.getJsonObject(i);
String pathSuffix = rec.getString("pathSuffix");
logger.info(" the pathSuffix value is '{}' ", pathSuffix );
}
I want to use the javax.json.JsonObject and not org.json.JsonObject.
So, the problem is in new JsonObject(response); ==> Cannot instantiate the type JsonObject.
I know that org.json.JSONObject has a constructor that takes a String, but I think not the case when using javax.json.JsonObject.
How can I correct my code to make JsonObject jsonObject = new JsonObject(response) take a String and stay using javax.json.JsonObject class?
According to its API instead of using JsonObject jsonObject = new JsonObject(response); you can instantiate it from your response-String like this:
String response = sb.toString();
StringReader reader = new StringReader(response);
JsonReader jsonReader = Json.createReader(reader);
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();

Parse Json array in android / java file

I am facing a problem to reach to an object which is inside an array of another object of another array. To make it simpler i am attaching the image (attached below), basically i want to reach to json object "0" inside jsonarray ticket itmes.
my codes are
JSONArray jsonArray = new JSONArray(buffer.toString());
JSONObject jsonobject = null;
jsonobject = jsonArray.getJSONObject(0);
JSONArray jsonarray1 = new JSONArray(buffer.toString());
jsonarray1 = jsonobject.getJSONArray("ticketitems");
JSONObject jsonobject1 = null;
TicketItem ticketItemList = new TicketItem();
jsonobject1 = jsonArray.getJSONObject(0);
ticketItemList.setItemCount(jsonobject1.getInt("itemCount"));
TicketItemList.add(ticketItemList);
However, jsonarray1 generates an exception stating
org.json.JSONException: No value for ticketitems
enter image description here
replace
jsonarray1 = jsonobject.getJSONArray("ticketitems");
with
jsonarray1 = jsonobject.getJSONArray("ticketItems");
It's case sensitive. It should be
jsonarray1 = jsonobject.getJSONArray("ticketItems");

How to get ArrayList<String[]> from a JSONObject

Actually, I have a JSONObject like this:
JSONObject json = new JSONObject();
json.put("type", "login");
json.put("friendList", FriendList);
and the FriendListis the type of ArrayList<String[]>
, then I use a socket to transfer JSON to my client.
My client received the data:
JSONObject receive_msg = new JSONObject(data);
String type = receive_msg.getString("type");
My question is how to get friendList with data typeArrayList<String[]>?
Thanks a lot if anyone helps.
you need to use JsonArray, iteratore over your list and fill the jsonArray then put it in the JsonObject
http://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html

parsing of string into json in android

here is my code..in android
String
result[{"Submitted_Date_Time":"12\/3\/2012","City":"","Issue_Category":"Graffity","OnProgress_Date_Time":"","id":"000000000000000","area":"SH 55","State":" ","Issue_Description":" ","Closed_Date_Time":"","imagepath":"android.graphics.Bitmap#40d55cd8","Latitude":"23.71","Longitude":"72.04","Issue_Status":"Closed","LandMark":" "}]
and i try to convert it in to json array and when i want to retrive json object from json array it gives me nullpointer exception...
JSONArray jarray = new JSONArray(result);
JSONObject jobj = jarray.getJSONObject(1);
plz help me.. thnkx in advance..
first your json String if it's contain "result" then it is not valid you can check it here http://jsonviewer.stack.hu/
to make valid json string just use String.replace as:
String finaljson=result.replace("result", "");
now JSON String is valid you can parse it as:
JSONArray jsonarray = new JSONArray(finaljson);
for (int i = 0 ; i < jarray.length() ; i++) {
JSONObject jsonobj = jarray.getJSONObject(i);
// get value from json object here
String str_City=jsonobj.getString("City");
///....
}
The Json array contains only one entry, the index is 0
JSONArray jarray = new JSONArray(result);
JSONObject jobj = jarray.getJSONObject(0);
To handle it right, access the json array using a for loop
JSONArray jarray = new JSONArray(result);
for (int i = 0 ; i < jarray.length() ; i++) {
JSONObject jobj = jarray.getJSONObject(i);
.....
}
Update your below code line it will solve your problem.
JSONObject jobj = jarray.getJSONObject(0);
or you can write below code instead of your above code line if object is more than one.
for(int i=0;i<jarray.length();i++){
JSONObject jobj = jarray.getJSONObject(i);
}

Android ArrayList<String[]> to PHP

I need my app to send an ArrayList<String[]> to php, I have this to call the service:
ArrayList<String[]> Items = new ArrayList<String[]>();
(...)
JSONObject JSONSend= new JSONObject();
JSONSend.put("Items", Items );
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpPost post = new HttpPost(SERVICE);
post.setHeader("json", JSONSend.toString());
StringEntity se = new StringEntity(JSONSend.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
and on the PHP service:
$data = file_get_contents('php://input');
$json = json_decode($data);
$Items = $json->{'Items'};
error_log($Items);
and the php is returning this:
[[Ljava.lang.String;#413e2fd0, [Ljava.lang.String;#413a2940, [Ljava.lang.String;#4139df18, [Ljava.lang.String;#4141b5b0, [Ljava.lang.String;#413931c8, [Ljava.lang.String;#41348b40, [Ljava.lang.String;#41393928]
The type of the $ServMade is string, so how can I take care of the data as an array on php? Am I missing something?
Try the following when generating json string in android:
JSONObject JSONSend= new JSONObject();
JSONArray ja = null;
JSONArray tmp = new JSONArray();
for(String s[] : Items){
ja = new JSONArray();
for(int i = 0; i<s.length; i++)
ja.put(s[i]);
tmp.put(ja);
}
JSONSend.put("Items", tmp);
The problem here is that You call .toString() (within Java) on an array of strings (String[]) that while NOT overrided returns exactly what You get in the JSON: [Ljava.lang.String;#413e2fd0].
Don't know exactly the JSONObject but I guess You should transform the ArrayList<String[]> (so the array of arrays of strings) to something different for JSONObject to handle it correctly.
Also, in PHP, You do not have to call $Items = $json->{'Items'}; - it is okay to call $Items = $json->Items;.

Categories