Working on a project where i am performing some operation based on instruction code. there are some json keys. where i am getting all the required values but have problem to get one among all. I am a initial level developer here.
Note : at everytime when i try to get instruction value in my android code i get 0.can anybody suggest me how should i go through now.
You can refer screenshot for my code.
From server I am getting proper json response.
{
"success": "true",
"error": "",
"result": [
{
"message": "Network is requesting permission to connect to your phone",
"instruction": 111,
"imei_no": "b2b5e4012e3c8b49",
"socket_user_id": "u566135811c9a2"
}
]
}
You are accessing the JSON value with not the correct key.
The correct way to get the key value is:
int instruction= json.getJSONArray("Result").getJSONObject(0).optInt("instruction")
Global version:
json.getJSONArray("Result").getJSONObject(index_of_array).optInt("instruction")
public long optLong (String name)
Returns the value mapped by name if it exists and is a long or can be coerced to a long, or 0 otherwise. Note that JSON represents numbers as doubles, so this is lossy; use strings to transfer numbers via JSON.
http://developer.android.com/reference/org/json/JSONObject.html#optJSONArray(java.lang.String)
Try this Hope this will Work!
final JSONObject obj = new JSONObject(response.toString());
final JSONArray array= obj.getJSONArray("result");
final int n = array.length();
for (int i = 0; i < n; ++i) {
final JSONObject result= array.getJSONObject(i);
System.out.println(result.getString("message"));
System.out.println(result.getString("instruction"));
}
It looks like you're not retrieving "result" from json. You'll need to retrieve result, which should give you an array, and then retrieve the first object of the array, in order to retrieve its property instruction.
Its a result of optInt method:
public int optInt(java.lang.String key)
Get an optional int value associated with a key, or zero if there is no such key
or if the value is not a number. If the value is a string, an >attempt will be made to evaluate it as a number.
You should get JsonArray "Result" and next get first JsonObject. Now, you can access to "instruction".
Related
Hi, I have a JSONObject that has multiple arrays in it. I want to get the name of each array as a string does anyone know how I can do this?
Here's how my json looks. so the value I'm trying to get out is the name of the array so B or C in this case. the purpose of this is to set the text of a header on a list view to this value.
{"Contacts": //JSONObject
{
"B"://JSONArray..
[
{"ContactName":sdfsdf,"ID":900,"Number":1368349},
{"ContactName":adsdfd,"ID":1900,"Number":136856},
{"ContactName":adglkhdofg,"ID":600,"Number":136845}
],
"C":[
{"ContactName":alkghoi,"ID":900,"Number":1368349},
{"ContactName":wetete,"ID":1900,"Number":136856},
{"ContactName":dfhtfh,"ID":600,"Number":136845}
]
.....//and so on..
}
}
You can use the JSONObject method names() to return an array of the string names in the object.
Example JSON Page
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
This code returns the address correctly. How can I get the post code long_name which is inside address_components?
Solution
I had to get each array, and then get the post code value.
I am using the value 7, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
reader.getJSONObject(1).getJSONArray("address_components");
Your problem is that results is a JSONArray that contains a child JSONObject composed of several children: "address_components", "formatted_address", "geometry", and "types". The result array actually contains many of these such objects, but let's focus on just the first child for now.
Look carefully at your code. With this line:
JSONArray resultArry = reader.getJSONArray("results");
You are getting the entire results. Later on, you then call the same method again:
JSONArray postCodeArray = reader.getJSONArray("address_components");
But you're asking for an "address_components" from the reader, where I do not expect you'll find anything (having already read the entire result before.) You should instead be working with the JSONArray you already got before, since it already contains the entire result.
Try something like:
JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");
Note: I don't know why you're singling out JSONObject #1 (as opposed to 0, which is the first, or any other one of them) and I also am not sure why you named the String postCode. So if I've misunderstood your intention, I apologize.
Is difficult to find the error... because all looks well. The problem maybe can exist when you make the json.put("address_components", something);
So my advice is put a breakpoint at this line
JSONArray postCodeArray = reader.getJSONArray("address_components");
o display the json in logcat
Log.d("Simple", reader.toString());
Then Paste your json in this web page to view more pretty
http://jsonviewer.stack.hu/
and check if all keys are stored well.
Solution
Need to get each array, and then get the post code value. The value 7 is used, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
I have this JSON string that I am recieving after I make a purchase from the playstore and I am apparently missing something in my code when I am trying to parse it.
PurchaseInfo:{"orderId":"12999763165555505758.1317333586444405",
"packageName":"com.mypkgname.myapp",
"productId":"monthly_purchase_01",
"purchaseTime":1357456489000,
"purchaseState":0,
"purchaseToken":"yrynypfkdncvhlxdbypysvwz.AO-J1OxFkndfqkClAqbbYAOApkMgTG4VX9Ef0uNP0FIs9-xGrXivkbx3FNMA2yNU12K_sbvRGFcknVBTfisI-uZawCXLGlMX4v4Zw8GFOmS0Q6PIbiITTGqn5h1QbEB4Rv84sXdUJHP3B_UQfujZN7ADi9bm_N4_iA"}
Here is the snippet of code I am using it to attempt the parsing
try {
JSONObject j1 = new JSONObject(tester1);
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
int count = mPurchInfo.length();
final String[] purchInfo = new String[count];
JSONObject q1 = mPurchInfo.getJSONObject(0);
purchInfo[0] = q1.getString("orderId");
purchInfo[1] = q1.getString("packageName");
purchInfo[2] = q1.getString("productId");
purchInfo[3] = q1.getString("purchaseTime");
purchInfo[4] = q1.getString("purchaseState");
purchInfo[5] = q1.getString("purchaseToken");
orderID=purchInfo[0];
} catch (JSONException e) {
Log.e("Error","Yes");
}
I am catching the an error as I see this last log statement in my log but I am still trying to learn the parsing JSON Strings
I hope I am at least close
Ideally I would like to have Strings set to all the values in the JSON String
orderID = ??
packageName = ??
etc.
Thanks
I have this JSON string that I am recieving after I make a purchase from the playstore
If that's really what you get back, you need to contact them and tell them to fix their API; that string is not valid JSON. There are two problems with it:
A JSON document must have an object or array as the top-level item. The string as quoted is missing a { at the beginning and a } at the end.
All keys in JSON must be in double quotes. The first one, PurchaseInfo, is not.
Also, your code is doing this:
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
...but if it were valid JSON, PurchaseInfo wouldn't be an array, it'd be an object.
Looking at it, if you remove the PurchaseInfo: at the beginning, it's valid. Once you've removed that, this line:
JSONObject j1 = new JSONObject(tester1);
...will give you an object from which you can query information:
String orderId = j1.getString("orderId");
I'm doing an application that need to receive an unknow number of names with they and a id.
I have solved the php and mysql part and this is what I receive into my app:
[{"id":"3","nombre":"Kaotik Sabadel"},{"id":"4","nombre":"Promotor Kaotik"}]
In the android part I start with this:
myJsonObj = new JSONObject(jodata);
and that's all I have.
And I want to set the names (nombre) into an spinner and when the user choose this name, get the value of his id...
You need to implement a custom SpinnerAdapter which parses the JSONArray (and no JSONObject) and fills the data into your Spinner.
As a little hint how to parse the data use this code:
JSONArray data=new JSONArray(json);
for(int i=0; i<data.length(); i++) {
JSONObject element=data.getJSONObject(i);
int id=element.getInt("id");
// ...
}
The part with the id may failes because it is a string and no integer just now I don't know if JSONObject can detect that the value can be casted to an int. If not use getString and parse it to a int.
public void HelloWord {
for (int i = 0; i < 20; i++) {
Log.d("Great");
}
}
The code above doesn't work why?
I try to get value name
Does anybody know where is the problem?
org.json.JSONException: Value ...Content of link... at
org.json.JSON.typeMismatch at org.json.JSONArray.
I prefer to use the GSON library, as it is a fast and effective JSON parser. Once added to the project you will need to create classes to represent the data returned. You then can call a single function to create your objects for you:
gson.fromJson();
An exceptionally good article on the use of GSON can be found at http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html - it even uses Twitter for the example.
I think that you are missing the way that JSON works. Anything in {} is an Object, while [] designates an array. So the root of the twitter feed is a JSONObject, NOT a JSONArray:
Try something more like this:
JSONObject obj = new JSONObject(mStringBuilder.toString());
JSONObject trends = obj.getJSONObject("trends");
JSONArray today = trends.getJSONArray("2012-04-10");
for (int i = 0; i < today.length(); i++) {
JSONObject tag = today.getJSONObject(i);
String name = tag.getString("name");
// do whatever with name
}
Much easier, and its clearer how it works. JSONObjects are dictionaries, with a simple mapping between keys and values - each Object ({}) can contain either more objects, or arrays ([]) which can contain either simple integers or more objects