Basically I want to convert a JSONObject json into an integer (127181078). When I use this code:
int intOfReceivedID = Integer.parseInt(json);
I get this error message:
java.lang.NumberFormatException: Invalid int: 127181078"
When I use this code:
char[] charArray = json.toCharArray();
String stringCharArray = charArray.toString();
testTextView.setText(stringCharArray);
testTextView gives me: [C#2378e625
However, when I use this code:
preprocessedjson = String.valueOf(json);
testTextView.setText(preprocessedjson);
The TextView gives 127181078, but I get the some error when I parse the text to an integer.
Can anybody tell me what going on here?
And could you help me convert my JSONObject into an integer?
This is the php code:
$myfile = fopen($filename, 'r') or die("Unable to open file!");
echo fread($myfile,filesize($filename));
fclose($myfile);
This is the the makeHttpRequest:
JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);
This question is confusing but from your error message it looks like this is a Java question that has nothing to do with JSON since your json String in this case looks like it does not in fact contain json(from the exception message).
It looks like the issue is your json value is a number plus additional spaces which Integer.parseInt does not handle.
Try
Integer.parseInt(json.trim())
int intOfReceivedID = Integer.parseInt(json);
I get this error
message:
java.lang.NumberFormatException: Invalid int: 127181078"
This happens because there is a new-line character at the end of the ID which can not be parsed into an Integer.
When I use this code:
char[] charArray = json.toCharArray();
String stringCharArray = charArray.toString();
testTextView.setText(stringCharArray);
testTextView gives me: [C#2378e625
By default, calling toString() on an object prints the memory location of the object (in this case [C#2378e625). That's what's being displayed in the TextView.
However, when I use this code:
preprocessedjson = String.valueOf(json);
testTextView.setText(preprocessedjson);
The TextView gives 127181078, but I get the some error when I parse
the text to an integer.
You'll get an error when parsing the text to an integer because it still has an invalid new-line character at the end.
If you are receiving a JSONObject from the server which only contains a long, then you can use the getLong() or optLong() methods to retrieve the integer value. The JSON parser automatically handles all the parsing and you don't need to do any additional work.
JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);
final long receivedId = json.optLong();
Related
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".
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");
Not able to get name/value pairs from JSON object, when using the variable but able to read it when hard coding the name.
To better explain :
1) My JSON object is like this -
{.....
{ "rates":{ "name1": value1, "name2": value2 ...etc }
...}
2) I am able to read this object in my android app.
3) Now this rate object name value pairs, i am trying to read based on user input -
String s1 = '"'+name1+'"'; // here name1 i got from user input, & converted into string
4) Now when i am trying to get the value from rates object, i am getting null exception -
JSONObject rateObject = jObject.getJSONObject("rates"); //able to get
complete object
String rate1 = (String) rateObject.get(s1); // giving NULL exception
5) But if i use hard code string, it works -
String rate1 = (String) rateObject.get("name1"); // working
Any pointers why its not working while using variable.
thanks
Thanks for suggestions, i sorted out the problem. There are 2 mistakes i was doing - 1) Using the quotes as correctly pointed out by others and 2) casting the double value to string. Correcting both has resolved my problem :)
In terms of your final code snippet, you are actually doing
String rate1 = (String) rateObject.get("\"name1\""); //note the extra quotes
because you have bookended the user input string with double-quote characters. You just want the input string itself with no bookending. The quotes in the JSON notation serve to delineate each key name; the quotes are not part of the key name itself.
You need to omit the quotes when you create s1:
String s1 = name1;
Or, if name1 is not a String already:
String s1 = name1.toString();
Replace:
String s1 = '"'+name1+'"';
with:
String s1 = name1;
Okay I am quering data from a Grails webservice that returns JSON. The JSON when viewed with the JSONViewer app parses fine. When I take that same string and use JSONObject(string) in my Android app I get "value of String cannot be converted to JSONObject."
Here's my JSON string
[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]
Now the JSON is comes from the standard JSON conversion of a SQL data using render from the groovy file through the import grails.converters.JSON.
... //(call to render JSON in the groovy file)
def a
a = Table.findAll("from someTable as st where st.id=" params.id)
render a as JSON
...
So I am not sure what I doing wrong and why the JSON looks a little off to me. (still new to JSON)
In json if you see "[]" means its a json array and if you see "{}" it is an json object. Both of then can have the other nested inside then.
In your case the string the starts with json array.
So try something like the following
String str = "[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]";
JSONArray jsonArray = new JSONArray(str);
jsonArray = jsonArray.getJSONArray(0);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String class = jsonObject.getString("class"); // class will value "mygrails.TopTen"
Try to create an JSONArray from the String instead of JSONObject. I didn't test this but that should do the trick: you have two nested arrays that contain then actual data.
Check out your JSON online with http://jsonformat.com/
http://www.freeformatter.com/json-formatter.html
JSON Viewer
http://jsonviewer.stack.hu/
Paste your text in there and you can see what you should parse: