JSONObject not workign - java

I am building an app for android.
I fire and HTTP GET request and this request returns a JSONObject. I want to retrieve the value by key. But this is not working properly.
This is the JSONObject named obj that I receive:
{"id":1,"name":"math","description":"This is a math course."}
If I log Log.d("title", String.valueOf(obj.has("name"))); this will result into true.
This works for all keys in the JSONObject.
But if I want to receive the name and do this so:
Log.d("title", obj.getString("name"));
I will get an unhandled exception: org.json.JSONException.
Does anybody know how I can fix this problem?

Maybe you should try someting like this:
Log.d("title", obj.name);

var obj = $.parseJSON('{"id":1,"name":"math","description":"This is a math course."}');
alert(obj['name']);
Try this :) You can use JSON.parse insted of $.parseJSON if you are not using jquery. Following in Java
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}

Everything between the { } makes part of an array, so you first need to get a JSONArray like this:
JSONArray myJSONArray = obj.getJSONArray();
And then you can access the field values with:
myJSONArray.getString("name") etc...
Search on google how to work with JSONArray.

Related

How to search a specific part of a JSON object and add to an already existing object

I'm new to using JSONs and I'm having a bit of difficulty. I am using the Kitsu API and parsing the JSON I get when I login. When I parse my json the image below pops up, but inside the 1 object array I want to get the large url in the avatar object inside of the attributes object and I don't know how.The beginning of the JSON, The middle of the JSON, The end. Lastly, I want to know how to edit the slug part of the JSON, if you don't know that's cool the main thing is getting the avatar url.
Picture of my error
Please, try this...
JSONObject myObject = new JSONObject(jsonStr);
JSONArray myArray = myObject.getJSONArray("data");
JSONObject obj = myArray.getJSONObject(0);
String id = obj.getString("id");
String type = obj.getString("type");
//change the lines bellow
JSONObject attributes = obj.getJSONObject("attributes");
JSONObject avatar = attributes.getJSONObject("avatar");
String large = avatar.getString("large");

How to get value by key from JSON?

JSON looks like:
{
"cover":"blabla.jpg",
"content":[
{
"article":"article_text",
"document":"document_text"
}
]
}
I know how to get "cover":
JSONObject json = new JsonObject(jsonStr);
json.get("cover");
But how can I get value by "article" key?
You can try something like this:
yourJSonObject.getJSONObject("cover").getJSONObject("content").getJSONObject("article");
Oh, i did it. Thanks.
json.getJSONArray("content").getJSONObject(0).getString("article")
"content" in that position it´s just a String, so at first place you have to create a new JSONObject from that String and then you can access to his properties like this
JSONObject content = new JSONObject(yourJSonObject.getString("content"));
String article = content.getString("article");

How to access nested objects of a Json File

the string I have into "jsonString" is the content of this link: http://85.18.173.82/cineca/wp5/json/events.json
Now I want the value "Day" of the second "Event".
JSONObject o = new JSONObject(jsonString);
String day = o.getString("XXXXXXXXXX");
System.out.println(day);
What does I have to put as argument of o.getString?
Many thanks
JSONObject obj = new JSONObject(json);
JSONArray array = obj.getJSONArray("Events");
for(int i = 0 ; i < array.length() ; i++){
System.out.println(array.getJSONObject(i).getJSONObject("Event").getString("Day"));
}
In this way, you can access, thanks.
The way you're constructing your JSONObject is wrong. By using this constructor you're not reading the json from that URL, you're actually using that string as a json representation (which it is not).
If you want to first read the json from your URL you'll have to do an HTTP GET request and then construct a JSONObject out of the response.
For more info, take a look at JSONObject docs

Removing the end [ and ] from php Json result for Android Java code

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'];

How to nest objects when building JSON with JSONObject

I'm trying to encode this string for a POST request. Can anyone tell me how I can encode
{"jsonrpc": "2.0", "method": "Files.GetSources", "params":{"media":"music"}, "id": 1}
So far I have
JSONOjbect obj = new JSONObject();
obj.put("jsonrpc", "2.0");
obj.put("method", "Files.GetSources");
But I'm not sure how to put in the rest - can anyone help?
If you're asking how you'd put the nested params object in there, you'd probably do:
JSONObject params = new JSONObject();
params.put("media", "music");
obj.put("params", params);
To use an array (per your comments below), you'd do something like this:
JSONArray properties = new JSONArray();
properties.put("resume");
properties.put("genre");
properties.put("studio");
...
JSONObject params = new JSONObject();
params.put("properties", properties);
obj.put("params", params);
JSONOjbect obj = new JSONObject().put("jsonrpc", "2.0")
.put("method", "Files.GetSources").put("id", 1)
.put("params", new JSONObject().put("media", "music"));
Chaining .put() like this is possible because put() returns the object it was called on - for this exact purpose.
You have two choices. You can create another object that holds "media":"music" and then put that in the original JSONObject or you can just pass this whole string into the JSONObject constructor and have it parse it for you.
Well, if you do have the string before hand, you can simply do
JSONObject object = JSONObject.getJSONObject("{\"jsonrpc\": \"2.0\", \"method\": \"Files.GetSources\", \"params\":{\"media\":\"music\"}, \"id\": 1}");

Categories

Resources