In my android project, I have an activity in which I want to obtain data from database using a PHP script. I manage the result of the script in this line :
String result = EntityUtils.toString(entity);
I created the jsonObject :
JSONObject jsonObject = new JSONObject(result);
I print this line and get: {"id":"1"}{"id":"2"}{"id":"3"}
But when I do this:
int i;
for(i=0;i<array.length;i++)
{
array[i] = "ID : "+jsonObject.getString("id");
}
I obtain "id : 1" three times, so I think there are some errors in the cycle..
the code of script php is here :
#Get the first row of the results
while ($row = mysqli_fetch_row($data)) {
#Build the result array (Assign keys to the values)
$result_data = array(
'id' =>$row[0],
);
#Output the JSON data
echo json_encode($result_data);
change to:
int i;
for(i=0;i<array.length;i++)
{
jsonObject=array[i];
String s = "ID : "+jsonObject.getString("id");
}
{"id":"1"}{"id":"2"}{"id":"3"}
is no valid code for a single JSON object - see here: JSON syntax.
I can only guess what you try to achieve, but I would guess your intention is to have a JSON array with 3 objects, each having an "id" value. The JSON code for such a structure should look like this:
[{"id":"1"},{"id":"2"},{"id":"3"}]
If you can make "EntityUtils.toString(entity)" to return the above JSON code, the following loop should also work:
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
System.out.println("ID : "+jsonObject.getString("id"));
}
edit
On a side note: I believe you get the result you describe, because when you call
new JSONObject(result);
where the result is a String that consists of
{"id":"1"}{"id":"2"}{"id":"3"}
then most likely JSONObject stops parsing the JSON code after the first right brace without throwing a parse exception. So it actually only parses the first JSON object and because of this you get "id : 1" three times. Personally I would consider this behavior a bug, so consider reporting it.
Related
I am trying to get json data from a fake api call and need to get the count of the items in it(so that in future I can call the actual restful service). I am not able to get the number of departments in the json. I am expecting the result as 4(int) here.
I am not able to get the string value(json) for the code below:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
Please find below the entire code:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
JSONObject jsnobject = new JSONObject(json);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
JSON Sample:
{
"Department":
[
{"SectionId":"1","SectionName":"Childrens Wear"},
{"SectionId":"2","SectionName":"Womens Wear"},
{"SectionId":"3","SectionName":"F&A"},
{"SectionId":"1","SectionName":"Mens Wear"}
]
}
I am new to java as well as api's.
Thanks,
You are either using incorrect key in code or you posted incorrect JSON example. You used locations as the key incode however there is no value against that key in sample JSON. You need to use Department as the key.
JSONArray jsonArray = jsnobject.getJSONArray("Department");
I've got a JSONArray that I pull from a server, it is a report of the emails I send to the server. My goal is to go through it, pick the one with a specific subject and print the "recieved" number from that element of the array. The JSON looks like this:
[
{"rejections":58,"timestamp":"2014-08-08 12:46:26","subject":"2014/08/08 12:46:03.604: apitest ACTION_100_","clicks":0,"opens":28,"streams":0,"received":86,"bounces":0,"complaints":0,"unsubs":0}
{"rejections":77,"timestamp":"2014-08-11 13:54:49","subject":"2014/08/11 13:54:25.786: apitest ACTION_100_","clicks":0,"opens":14,"streams":0,"received":91,"bounces":0,"complaints":0,"unsubs":0}
]
I'm basically trying to echo the number associated with "recieved": where the subject is "2014/08/11 13:54:25.786: apitest ACTION_100_" ... I don't know how to do the if statement. I know it will look something like:
if(thisElement["subject"].equals("2014/08/11 13:54:25.786: apitest ACTION_100_")){
echo thisElement["recieved"];
}`
My code:
//json = the first code block in this post
//newSubj = the subject I mentioned above
JSONArray json = readJsonFromUrl(serverStats);
for (int i = 0; i < json.length(); i++)
{
JSONObject obj = json.getJSONObject(i);
//if(obj["subject"].equals(newSubj)) <----- ?
System.out.println(obj.toString()); // should this be obj["recieved"].toString()?
}
http://www.json.org/javadoc/org/json/JSONObject.html
if (newSubj.equals(obj.get("subject")) {
int received = obj.getInt("received");
System.out.println(received);
}
My PHP code is this:
$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status");
#$row = mysql_fetch_row($userdetails) ;
while($rows=mysqli_fetch_array($userdetails)){
$status[]= array($rows['Aircraft']=>$rows['Status']);
}
#Output the JSON data
echo json_encode($status);
and gives this:
[{"A70_870":"1"},{"A70_871":"1"},{"A70_872":"1"},{"A70_873":"1"},{"A70_874":"1"},{"A70_875":"1"},{"A70_876":"2"},{"A70_877":"1"},{"A70_878":"2"},{"A70_879":"2"},{"A70_880":"2"},{"A70_881":"0"},{"A70_882":"0"},{"A70_883":"0"},{"A70_884":"0"},{"A70_885":"0"}]
The java code that reads it is this:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
n870 = jsonObject.getInt("A70_870");
n871 = jsonObject.getInt("A70_871");
n872 = jsonObject.getInt("A70_872");
n873 = jsonObject.getInt("A70_873");
n874 = jsonObject.getInt("A70_874");
n875 = jsonObject.getInt("A70_875");
n876 = jsonObject.getInt("A70_876");
n877 = jsonObject.getInt("A70_877");
n878 = jsonObject.getInt("A70_878");
n879 = jsonObject.getInt("A70_879");
n880 = jsonObject.getInt("A70_880");
n881 = jsonObject.getInt("A70_881");
n882 = jsonObject.getInt("A70_882");
n883 = jsonObject.getInt("A70_883");
n884 = jsonObject.getInt("A70_884");
n885 = jsonObject.getInt("A70_885");
When i run my android app I seem to keep getting the error:
"of type org.json.JSONArray cannot be converted into Json object"
However when I send the app dummy code without the square brackets, it seems to work fine! How do I get rid of those [ and ] brackets on the ends???
Alternatively is there a way to accept the json as it is and adapt the java to read it?
echo json_encode($status, JSON_FORCE_OBJECT);
Demo: http://codepad.viper-7.com/lrYKv6
or
echo json_encode((Object) $status);
Demo; http://codepad.viper-7.com/RPtchU
Instead of using JSonobject, use JSONArray
JSONArray array = new JSONArray(sourceString);
Later loop through the array and do the business logic.
http://www.json.org/javadoc/org/json/JSONArray.html
Maybe with this kind of json structure?
$status[$rows['Aircraft']]= $rows['Status'];
You get an JSONArray, Not Object, you could create an Object holding an array, or parsing the array.
Refering to this post
Solution #1 (Java)
How about a helper method like this:
private int getProp(String name, JSONArray arr) throws Exception {
for (int i = 0; i < arr.length(); ++i) {
JSONObject obj = arr.getJSONObject(i);
if (obj.has(name))
return obj.getInt(name);
}
throw new Exception("Key not found");
}
Then you could use it like:
JSONArray jsonArray = new JSONArray(result); // note the *JSONArray* vs your *JSONObject*
n870 = getProp("A70_870", jsonArray);
n871 = getProp("A70_871", jsonArray);
...
Note I haven't tested this code, so you may need to make some changes...
Alternate solution (PHP)
It's been awhile since I've worked with PHP, but you might be able to leave your Java code intact and change your PHP int the while-loop body to:
$status[$rows['Aircraft']] = $rows['Status'];
I want to know if it is possible to check if some key exists in some jsonArray using java. For example: lets say that I have this json string:
{'abc':'hello','xyz':[{'name':'Moses'}]}
let's assume that this array is stored in jsnArray from Type JSONArray.
I want to check if 'abc' key exists in the jsnArray, if it exists I should get true else I should get false (in the case of 'abc' I should get true).
Thnkas
What you posted is a JSONObject, inside which there is a JSONArray. The only array you have in this example is the array 'xyz', that contains only one element.
A JSONArray example is the following one:
{
'jArray':
[
{'hello':'world'},
{'name':'Moses'},
...
{'thisIs':'theLast'}
]
}
You can test if a JSONArray called jArray, included inside a given JSONObject (a situation similar to the example above) contains the key 'hello' with the following function:
boolean containsKey(JSONObject myJsonObject, String key) {
boolean containsHelloKey = false;
try {
JSONArray arr = myJsonObject.getJSONArray("jArray");
for(int i=0; i<arr.length(); ++i) {
if(arr.getJSONObject(i).get(key) != null) {
containsHelloKey = true;
break;
}
}
} catch (JSONException e) {}
return containsHelloKey;
}
And calling that in this way:
containsKey(myJsonObject, "hello");
Using regular expressions will not work because of the opening and closing brackets.
You could use a JSON library (like google-gson) to transform your JSON Array into a java array and then handle it.
JSON arrays don't have key value pairs, JSON objects do.
If you store it as a json object you can check the keys using this method:
http://www.json.org/javadoc/org/json/JSONObject.html#has(java.lang.String)
If you use JSON Smart Library in Java to parse JSon String -
You can parse JSon Array with following code snippet -
like -
JSONObject resultsJSONObject = (JSONObject) JSONValue.parse(<<Fetched JSon String>>);
JSONArray dataJSon = (JSONArray) resultsJSONObject.get("data");
JSONObject[] updates = dataJSon.toArray(new JSONObject[dataJSon.size()]);
for (JSONObject update : updates) {
String message_id = (String) update.get("message_id");
Integer author_id = (Integer) update.get("author_id");
Integer createdTime = (Integer) update.get("created_time");
//Do your own processing...
//Here you can check null value or not..
}
You can have more information in - https://code.google.com/p/json-smart/
Hope this help you...
hello
i have an some 10 datas from db with attribute same attribute name
JSONObject json = new JSONObject();
json.put("text",value1);
json.put("title",value2);
json.put("url",value3);
i use this above code i am getting similar to this
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
while i parse it in php i am getting an null value i dont know y .. can you tell me where i am wrong...
your output should be something like this to be parsable
[{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}]
and for this you should be using JSONArray.
Basically you will have to create a JSON Array to hold your 10 datas, like so:
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 10; i++) {
JSONObject json = new JSONObject();
json.put("text",value1);
json.put("title",value2);
json.put("url",value3);
jsonArray.put(json);
}
Output, See Bala R's response.