This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 7 years ago.
In my project, I am getting the following JSON from the HTTP response.
{"base":"USD","date":"2015-04-24","rates":{"AUD":1.2827,"BGN":1.8069,"BRL":2.9733,"CAD":1.2119,"CHF":0.9551,"CNY":6.1948,"CZK":25.364,"DKK":6.8927,"GBP":0.6614,"HKD":7.75,"HRK":7.0284,"HUF":278.53,"IDR":12954.0,"ILS":3.9244,"INR":63.563,"JPY":119.51,"KRW":1078.25,"MXN":15.358,"MYR":3.5741,"NOK":7.8298,"NZD":1.3216,"PHP":44.281,"PLN":3.7076,"RON":4.08,"RUB":51.215,"SEK":8.6674,"SGD":1.3375,"THB":32.55,"TRY":2.7314,"ZAR":12.182,"EUR":0.9239}}
I want to get the "BGN" from the above json. How to get it.
There are multiple steps involved in this
First: Create a jsonObject
JSONObject jObject = new JSONObject(yourJSON_String);
Second: Get your desired Object or Array, in your case
obj = getJSONObject("rates")
Third: Get required String
obj.getString("BGN");
Here is the JSON CLASS REFERENCE
Assuming you are using JSONObject, and that your root document is called "doc",
JSONObject rates = doc.getJSONObject("rates") would get you the rates part:
{"AUD":1.2827,"BGN":1.8069,"BRL":2.9733,"CAD":1.2119,"CHF":0.9551,"CNY":6.1948,"CZK":25.364,"DKK":6.8927,"GBP":0.6614,"HKD":7.75,"HRK":7.0284,"HUF":278.53,"IDR":12954.0,"ILS":3.9244,"INR":63.563,"JPY":119.51,"KRW":1078.25,"MXN":15.358,"MYR":3.5741,"NOK":7.8298,"NZD":1.3216,"PHP":44.281,"PLN":3.7076,"RON":4.08,"RUB":51.215,"SEK":8.6674,"SGD":1.3375,"THB":32.55,"TRY":2.7314,"ZAR":12.182,"EUR":0.9239}
From this object you can then simply get the BGN value using
String bgn = rates.getString("BGN")
JSONObject responseJson = new JSONObject("<your-string">);
JSONObject ratesJson = responseJson.getJSONObject("rates");
double rate = ratesJson.getDouble("BGN");
To see the JSON object clearly, use PrettyJson. Copy paste the JSON string here and it will show you nested objects (if any) for clearly understanding the response.
Related
I have a Json string:
String json = "{\"I\":0,\"lst\":[{\"i1\":100500,\"s1\":\"abrakadabra\",
\"aList\":[{\"text\":\"secret will of my Dad\"}]}]}";
JSONObject o = new JSONObject(json);
My question: how, using Json Obj methods, to browse through each node element recursively?
Vitali, I don't have enough reputation points to reply to your comment, so posting it as an answer. In that post I linked, I meant the code snippet with loopThroughJson() method. I haven't tried it myself but that looks right. For completeness, this is the link again -
Recursively parsing JSON via JSONObject to fetch value against specific keys
Loop through the object, get child as reference of Object class using the get() method, if that object is instance of JSONObject or JSONArray, go deeper.
This question already has answers here:
Determine whether JSON is a JSONObject or JSONArray
(9 answers)
Closed 8 years ago.
Im working with an android app where i receive a json based response from a webservice. All was fine when the webservice returned more than one record in response as json array, the issue started when the web service started sending data which had only one record and it was sent as json object.On the client side i cant predict the number of records being returned(like 1 or more than 1) i want to find a solution which accommodates both conditions. The below code is the one i use to aprse the data when there are more than one records,
get_response = new JSONObject(webservice_out);
JSONArray inventory_data = get_response.getJSONArray("inventorydata");
Log.e("inventory", inventory_data.toString());
for (int j = 0; j < inventory_data.length(); j++)
{
JSONObject e1 = inventory_data.getJSONObject(j);
Log.e("names", e1.getString("itemName"));
JSONObject e3 = e1.getJSONObject("passenger");
}
In the above code "inventorydata" is one of the json value returned as a response from the webservice, whenever "inventorydata" hold only one record in response its being sent as json object, when it has more than 1 records its being sent as json array. Since the number of records in the response are dynamic , i want to find a solution which can hold both (json object and array) depending the response from the webservie.
Note: i dont have any authority to make changes to the webservice
You have two options:
Tell your server team to always send a json array, even if it only contains one item. This is the preferred solution because it enforces that the structure of the response does not change and allows clients to process it the same way every time.
Use get_response.optJSONArray() instead, then check if it's null. If it is, fall back to getJSONObject().
JSONArray inventory_data = get_response.optJSONArray("inventorydata");
if (inventory_data == null) {
// process json array
} else {
JSONObject jsonObject = get_response.getJSONObject("inventorydata");
// process json object
}
This question already has answers here:
Parsing JSON file in android
(4 answers)
Closed 7 months ago.
I need to call this URL: https://login.skype.com/json/validator?new_username=name.surname
I obtain a json file format. I need only to take the element associated to tag "status". For the above link is "status":406, so I need the value 406. What is the most simple way for implementing a parser that get only this element?
Simplest way to do it for this particular situation is
JSONObject obj=new JSONObject(myJSONString);
String status=obj.getString("status");
You'll have to handle the JSONException incase the tag "status" isn't found.
Have you got this response as a string yet? That is your first step but as you are asking for a parser I assume youve done this. If so the rest is easy:
String jsonString = parsedString; //The downloaded JSON String
JSONObject firstObj = new JSONObject(parsedString);
String status = firstObj.getString("status");
I have a string being returned from a HttpClient called data.
Data = {"result":[{"id":"2","contextID":"1","name":"Kitchen","image":"81"},
{"id":"1","contextID":"1","name":"Living Room","image":"18"},
{"id":"3","contextID":"1","name":"Toilet","image":"75"}]}
I am then performing this code:
resultArray = new JSONArray (data);
and returning this JSONArray. However, I get a JSONException error:
JSONObject cannot be converted to JSONArray
Surely this is a JSONArray not a JSONObject? Or is it a JSONObject of JSONObjects? I'm pretty new to JSON and I'm wanting to loop through and create new Locations using these imported values. Is there an easy or established way of doing this?
Many Thanks.
Data is a JSONObject, and Data["result"] is a JSONArray that contains JSONObjects.
Its a json object with a JSONArray of JSONObjects inside of it. { } means object and [] means array. So you get the top level string as a JSON object, then get the results parameter as an array, then get each index into the results as an object (and you can get the parameters of those via getString, etc).
Data is actually a JSONObject that contains a JSONArray named "result." If you wanted to get the JSONArray you'd have to do the following:
JSONObject dataObj = new JSONObject(data);
JSONArray dataArr = dataObj.getJSONArray("result");
For future reference, since you're new to JSON, data inside {} braces is a JSONObject and data inside [] braces is a JSONArray. Arrays and objects can be nested inside of each other and it's sometimes hard to read. I recommend formatting your data if you need help reading it. I personally use http://jsonformatter.curiousconcept.com/ to format and validate my data. I'm not associated with the site in any way. I just find it really useful.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sort JavaScript object by key
I am creating JSONArray from JSONObject in android. The JSONArray that i wanted to be is:
[{"last_name":"cruz",
"first_name":"juan",
"middle_name":"sam"}]
but it appears
[{"first_name":"cruz",
"last_name":"juan",
"middle_name":"sam"}]
how can I arrange the array in order that I wanted?
Thanks...
1. prepare a LinkedHashMap object with elements
2. convert it to JSONObject
Example:
Map obj = new LinkedHashMap();
obj.put("a", "String1");
obj.put("b", new Integer(1));
obj.put("c", new Boolean(true));
obj.put("d", "String2");
JSONObject json = new JSONObject(obj);
download this library:
https://github.com/douglascrockford/JSON-java
save all the files in a new package in your project
instead of using org.json.JSONObject use your.package.JSONObject which you added from the downloaded library.
now open JSONObject.java file and change HashMap() to LinkedHashMap() in the constructor
public JSONObject(Map map)
This will make the JSONObject store data in the order you entered the values using put.
You can't maintain the order of JSONObject response, because it is itself mentioned in the documents.
An object is an unordered set of name/value pairs.
I had faced the same problem and then i need to use either the gson library or to make json by ur logic..
An object is an unordered set of name/value pairs.
Best of luck.!