How to access the JSON element? - java

#Override
protected void onPostExecute(String response) {
String firstName = null;
String lastName = null;
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonArray = jsonResponse.getJSONArray("");
JSONObject userInfo = jsonArray.getJSONObject(0);
firstName = userInfo.getString("id");
lastName = userInfo.getString("id");
}
catch (JSONException e){
e.printStackTrace();
}
I have this JSON file https://api.myjson.com/bins/1a5t7w
How i can acces to thats values, i used this code but it doesn`t work?
It returns #null#

You are getting a JSON array in the response.
To parse this array you need to pass the response to JSONArray object like below
try {
JSONArray rspArr = new JSONArray(response);
for(int i= 0; i< rspArr.length(); i++){
JSONObject jsonObject = (JSONObject) rspArr.get(i);
//Your logic
}
}catch (Exception e ){
//log exception
}

// since you know is an array, create a JSONArray based on your response String
JSONArray array = JSONArray(response)
// obtain the first element of your array as a JSONObject
JSONObject jsonObject = array.getJSONObject(0)
// once you get the jsonObject you can start getting the values you need
String id = jsonObject.getString("id")
Hope it helps!

Answer by Arunangshu seems correct, you need to extract the JSONArray first because the API is returning JSONArray(array of JSON objects) and not one big JSON object.
One can use http://jsonviewer.stack.hu/ for viewing JSON. It gives better understanding of the JSON structure.
For Java, one can use http://www.jsonschema2pojo.org/ for converting JSON object(not array) to Java Pojo class (select the options carefully).
Following is the first object from json array -
{"id":48191,"title":"Apple Crumble Recipe","image":"https://spoonacular.com/recipeImages/48191-312x231.jpg","imageType":"jpg","usedIngredientCount":1,"missedIngredientCount":2,"missedIngredients":[{"id":4073,"amount":35.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Milk, Eggs, Other Dairy","name":"margarine","original":"35 g margarine or butter","originalString":"35 g margarine or butter","originalName":"margarine or butter","metaInformation":[],"meta":[],"image":"https://spoonacular.com/cdn/ingredients_100x100/butter-sliced.jpg"},{"id":8120,"amount":35.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Cereal","name":"rolled oats","original":"35 g rolled oats","originalString":"35 g rolled oats","originalName":"rolled oats","metaInformation":[],"meta":[],"image":"https://spoonacular.com/cdn/ingredients_100x100/rolled-oats.jpg"}],"usedIngredients":[{"id":9003,"amount":400.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Produce","name":"apples","original":"400 g cooking apples peeled cored and quartered","originalString":"400 g cooking apples peeled cored and quartered","originalName":"cooking apples peeled cored and quartered","metaInformation":["cored","peeled","quartered"],"meta":["cored","peeled","quartered"],"image":"https://spoonacular.com/cdn/ingredients_100x100/apple.jpg"}],"unusedIngredients":[],"likes":965}

Related

count key value in JSON and extract values

I have following JSONObject (not array, which I don't mind to convert). I am trying to do two things:
get the count of genre entry as "poetry" (count = 2).
get the key value of author name and genre:
authorName = malcolm
genreName = newsarticle
authorName = keats
genreName = poetry
{ "AddressBook" :{
"Details" :{
"authorname" :{
"Author-malcolm":{
"genre" :"poetry"
}
"Author-keats":{
"genre" :"poetry"
}
}
}
}
}
Code which I tried:
public static void main(String[] args) throws Exception, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("My path to JSON"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arrayhere = new JSONArray();
arrayhere.add(obj);
System.out.println(arrayhere);
int count = 0;
for(int i = 0; i < arrayhere.size(); i++) {
JSONObject element = arrayhere.getJSONObject(i);//The method getJSONObject(int) is undefined for the type JSONArray
String branchName = element.getString("genre");//The method getString(String) is undefined for the type JSONObject
if(branchName.equals("poetry")) {
count ++;
}
}
System.out.println("Count f0r poetry genre=" + count);
}
}
I have looked at solutions all over. There is no question similar to this at stackoverflow. I am not sure if the procedure is correct.
A few problems here.
First, I'm not sure where you got that example JSON but you can't work with that. That's not even valid JSON Formatting.
Looks like you want something like this:
{
AddressBook:
[
{
authorname: "author-malcom",
genre:"poetry"
},
{
authorname: "author-keats",
genre: "poetry"
}
]
}
That's the structure you're trying to create in JSON.
So, you're parsing this in from a file into a JSONObject that has a key called AddressBook inside of it. That key points to an array of JSONObjects representing authors. Each of those objects will have a key called genre. You're trying to access the genre key and count on a condition.
What you did above was create attempt to create a JSONObject from an invalid string, and then add the entire JSONObject itself into the JSONArray. JSONArray.add() doesn't convert an object to an array, it literally adds it onto the array.
jsonObj => {"Name":"name1","Id":1000}
jsonArray.add(jsonObj)
jsonArray => [{"Name":"name1","Id":1000}]
That's what you did in your code above. You didn't create an array from a JSONObject, you added an object to the array.
Proper use is going to look like:
Object obj = parser.parse(new FileReader("path_to_file"));
JSONObject jobj = (JSONObject) obj;
//access key AddressBook
JSONArray author_array = jobj.getJSONArray("AddressBook");
int poetry = 0;
for(int i = 0; i < author_array.length(); i++) {
JSONObject author = (JSONObject) author_array.get(i);
if(author.getString("genre").equals("poetry")) {
poetry++;
}
}
To summarize, you're problems come from a lack of understanding about JSON Formatting and how to access elements within a JSON Object.
Paste in the sample JSONObject I gave you above here. That site will let you visualize what you're working with.

Getting Json object inside a Json object in Java

So I have some code that is able to send this out:
{"id":1,
"method":"addWaypoint",
"jsonrpc":"2.0",
"params":[
{
"lon":2,
"name":"name",
"lat":1,
"ele":3
}
]
}
The server receives this JSON object as a string named "clientstring":
JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject
String method = obj.getString("method"); //Pulls out the corresponding method
Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method".
however both of these have given me exceptions:
String params = obj.getString("params");
and
JSONObject params = obj.getJSONObject("params");
I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand.
Any help is VERY appreciated, thanks!
params in your case is not a JSONObject, but it is a JSONArray.
So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject.
JSONObject obj = new JSONObject(clientstring);
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);
How try like that
JSONObject obj = new JSONObject(clientstring);
JSONArray paramsArr = obj.getJSONArray("params");
JSONObject param1 = paramsArr.getJSONObject(0);
//now get required values by key
System.out.println(param1.getInt("lon"));
System.out.println(param1.getString("name"));
System.out.println(param1.getInt("lat"));
System.out.println(param1.getInt("ele"));
Here "params" is not an object but an array. So you have to parse using:
JSONArray jsondata = obj.getJSONArray("params");
for (int j = 0; j < jsondata.length(); j++) {
JSONObject obj1 = jsondata.getJSONObject(j);
String longitude = obj1.getString("lon");
String name = obj1.getString("name");
String latitude = obj1.getString("lat");
String element = obj1.getString("ele");
}

simpleJson parsing in Java

I'm very new to parsing JSON. I have looked all over and cannot seem to grasp the idea to my particular problem. I'm having a hard time understanding how to get a JSON object from a JSON array. My example is below
[{"styleId":94,
"status":"verified",
"abv":"4.2",
"name":"Bud Light"}]
Here is my current code
JSONParser parser = new JSONParser();
Object obj = parser.parse(inputLine);
JSONObject jsonObject = (JSONObject) obj;
Long currPage = (Long)jsonObject.get("currentPage");
System.out.println(currPage);
JSONArray jArray = (JSONArray)jsonObject.get("data");
System.out.println(jArray);
inputLine is my orignal JSON. I have pulled a JSONArray out of the original JSONObject that has the "data" tag. Now this is where I'm stuck and given the JSONArray at the top. Not sure how to iterate through the Array to grab JUST the "name" tag.
Thanks for the help in advanced!
To iterate in a JSONArray you need to go through each element in a loop.
int resultSize = jArray.length();
JSONObject result;
for (int i = 0; i < resultSize; i++) {
result = resultsArray.getJSONObject(i);
String name = result.getString("name");
// do whatever you want to do now...
}
just use Gson . it works well out of the box with any object type you supply.
This is an example from the user's guide:
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

Android parse Json array of Strings

How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?
My Json to be parsed :
[
{
"streets": [ "street1", "street2", "street3",... ],
}
]
Later in my code I want to populated with that array a spinner item in my layout.
Everything i tried enden with only one street item listed in the spinner.
To parse
try {
JSONArray jr = new JSONArray("Your json string");
JSONObject jb = (JSONObject)jr.getJSONObject(0);
JSONArray st = jb.getJSONArray("streets");
for(int i=0;i<st.length();i++)
{
String street = st.getString(i);
Log.i("..........",""+street);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Once you parse and add it to array. Use the same to populate your spinner.
[ represents json array node
{ represents json object node
Try this..
JSONArray arr = new JSONArray(json string);
for(int i = 0; i < arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
JSONArray ar_in = c.getJSONArray("streets");
for(int j = 0; j < ar_in.length(); j++){
Log.v("result--", ar_in.getString(j));
}
}
We need to make JSON object first. For example,
JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length = " + arr.length());
for(int i=0;i<arr.length();i++)
{...
arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling

Parse json array from webserver

I'm going to parse a json array from web server to android app.The array looks like this
{"Level":
[
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]},
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]},
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]}
]
}
my java code is
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("Level");
rlevel = new ArrayList<LatLng>();
System.out.println("*****JARRAY*****"+jArray.length());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
jlat = json_data.getDouble("lat");
jlgn = json_data.getDouble("lgn");}
but not works! any idea?after this i want to save each route into an array (etc $plan[1]=first route from json, $plan[2]=second route from json)
Try something like this:
//code is a String where you saved the json
JSonObject json= new JsonParser().parse(code).getAsJsonObject();
JsonArray jArray= json.getAsJsonArray("Level");
rLevel=new ArrayList<LatLng>();
//notice the use of the size() method. There is not length() method defined for ArrayList
System.out.println("*****JARRAY*****"+jArray.size());
for(int i=0;i<jArray.size();i++){
//notice that inside the Level Array you have route-arrays
JSonObject level_item = jArray.get(i).getAsJsonObject();
JSonArray route= level_item.getAsJSonArray("route");
//now I don't know exactly what data you want to extract, since there are 2
//pairs of LatLng, for the first one:
jlat = route.get(0).get("lat").getAsDouble();
jlgn= route.get(0).get("lgn").getASDouble();
The exact names for methods and JsonObjects tend to differ from a library to another, but the principle is the same.
This parse task can be done very easily using droidQuery:
try {
JSONObject json = $.parseJSON(result);
if (json.has("Level")) {
Object[] datas = $.makeArray(json.getJSONArray("Level"));
for (Object data : datas) {
JSONObject obj = (JSONObject) data;
Object[] coordinates = $.makeArray(obj.getJSONArray("route"));
for (Object coord : coordinates) {
Map<String, ?> map = $.map((JSONObject) coord);
double latitude = (Double) map.get("lat");
double longitude = (Double) map.get("lgn");
//TODO: do something with these values
}
}
}
else {
Log.d("JSON", "Result does not contain 'Levels' variable");
}
}
catch (Throwable t) {
t.printStackTrace();
}

Categories

Resources