I need to get the string in extract object. but the JSON object contains some random variable, so when I call through JSONObject pg = qr.getJSONObject(0) I get an error stating I can't use an integer.
Here is the jsonobject:
{"query":
{"pages":
{"7529378":
{"pageid":7529378,
"ns":0,
"title":"Facebook",
"extract":"<p><b>Facebook</b> is an online social networking service.</p>"
}
}
}
}
I tried the following Key structure but failed.
Iterator<?> keys = pg.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
if( pg.get(key) instanceof JSONObject ){
// get all values from JSONObject
str=pg.optString("extract");
//get ns, title, extract,.. in same way from jObjpages
}
}
Do something like:
JSONObject json = new JsonObject(your_main_string);
JSONObject query= json.getJsonObject("query");
JSONObject pages = query.getJsonObject("pages");
JSONObject id= pages .getJsonObject("7529378");
String extract = id.getString("extract");
Related
I'm a android beginner and I'm doing to access a JSON file in and it has an error. I have a problem in parsing this
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray accounts = jsonObject.getJSONArray("account_data");
for(int i=0;i < accounts.length();i++){
JSONObject a = accounts.getJSONObject(i);
sin = a.getString("sin");
account_name = a.getString("account_name");
address = a.getString("address");
status = a.getString("status");
due_date = a.getString("due_date");
total_amount = a.getDouble("total_amount");
sin_lbl.setText(a.getString("account_name"));
}
here is the JSON File
{"account_data":{
"sin":"200111-102 ",
"account_name":"LUMABAN, CRISTOM ",
"address":"352 MABINI ST.,, SABANG, Baliwag ",
"status":"A ",
"due_date":"2019-04-23",
"total_amount":"491.00"
},"code":1101,"message":"Account Info Retrieved"}
I have an error in putting it in array.
Instead of using JSONArray , try to use JSONObject.
String[] array = {json.get("sin"), json.get("account_name"), json.get("address"), json.get("status"), json.get("due_date"), json.get("total_amount") }
{"account_data":{"sin":"200111-102 ","account_name":"LUMABAN, CRISTOM ","address":"352 MABINI ST.,, SABANG, Baliwag ","status":"A ","due_date":"2019-04-23","total_amount":"491.00"},"code":1101,"message":"Account Info Retrieved"}
Actually, it's a json object, not array. So that you can not convert json object to json array
Difference between Json Array and Json Object:
A JSONArray is an ordered sequence of values. A JSONObject is an unordered collection of name/value pairs.
JSONArray: Its external text form is a string wrapped in square brackets with commas separating the values.
JSONObject: Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
Please use this json parshing
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONObject accounts = jsonObject.getJSONObject("account_data");
sin = accounts.getString("sin");
account_name = accounts.getString("account_name");
address = accounts.getString("address");
status = accounts.getString("status");
due_date = accounts.getString("due_date");
total_amount = accounts.getDouble("total_amount");
sin_lbl.setText(a.getString("account_name"));
} catch (Exception e) {
}
if you asked about iterating on json object you could try this one
JSONObject jObject = new JSONObject(jsonStr);
JSONObject menu = jObject.getJSONObject("account_data");
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);
}
so now you have your data into as pair of key and value
if you have a json array of this response you could do as following
JSONObject root = new JSONObject("your root");
JSONArray resultArray = root.getJSONArray("your array key");
for (int i = 0; i < resultArray.length(); i++) {
// here to get json object one by one and access every item into it
JSONObject resultObject = resultArray.getJSONObject(i);
posterPath = resultObject.getString("key");
title = resultObject.getString("key");
releaseDate = resultObject.getString("key");
description = resultObject.getString("key");
voteAverage = resultObject.getDouble("key");
}
i have two situation of Json output .
one is data that found and i have a json array and a json object like this:
{"data":"yes"}[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]
other situation is that data not found :
{"data":"no"}
just one json object.
how parse this data in android client for support two situtaion?
First, you should validate your json in http://jsonlint.com/ if you test it you will look that is a wrong json. So, for make it right, in your server your response should look something like this:
{"data":"yes","response":[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
And in that case, in android
JSONObject jsonObj = new JSONObject(response);
if (jsonObj.getString("data").compareTo("yes") == 0) {
JSONArray jsonArray = jsonObj.getJSONArray("response");
//To-Do another code
}
and that's all
Here is a possible case: (you need to fix your json format)
Success -
string resultJSON =
{"success":true,
"data":[
{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},
{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
Failed -
string resultJSON =
{"success":false}
Then
JSONObject jsonRoot = new JSONObject(resultJSON);
bool isSuccess = jsonRoot.getBoolean("success");
if (isSuccess) {
// do the array parser
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonObj = jsonData.getJSONObject(i);
String id = jsonObj.getString("id"); // get the value of id
String desc = jsonObj.getString("desc"); // and so on...
}
}
I parse the response from a web service into a JSONObject, which when logged, looks as follows:
{"Preferences":"{Pref1=Apple, Pref2=Pear}"}
I understand how to ask for the Preferences tag e.g. jsonObject.get("Preferences"). However, I do not understand what object I am getting back nor how to iterate over it. How can I iterate over the object returned by jsonObject.get("Preferences")?
the object returned by preferences is a String. If you want to iterate through the childs of Preferences you may want to change the structure, to for example:
{"Preferences":{"Pref1":"Apple", "Pref2":"Pear"}}
and parse it like this:
JSONObject inputJSON = new JSONObject("{\"Preferences\":{\"Pref1\":\"Apple\", \"Pref2\":\"Pear\"}}");
JSONObject preferencesJSON = inputJSON.getJSONObject("Preferences");
Iterator<String> keysIterator = preferencesJSON.keys();
while (keysIterator.hasNext())
{
String keyStr = (String)keysIterator.next();
String valueStr = preferencesJSON.getString(keyStr);
}
alternatively, if you want to keep your structure, you can parse the returned string by the Preferences object like this:
JSONObject inputJSON = new JSONObject("{\"Preferences\":\"{Pref1=Apple, Pref2=Pear}\"}");
String preferencesStr = inputJSON.getString("Preferences");
JSONObject preferencesJSON = new JSONObject(preferencesStr);
Iterator<String> keysIterator = preferencesJSON.keys();
while (keysIterator.hasNext())
{
String keyStr = (String)keysIterator.next();
String valueStr = preferencesJSON.getString(keyStr);
}
You can't iterate through above JsonObject, but if it were like this
["Preferences":{"Pref1":"Juan", "Pref2":"JuanK"}]
you could have done like
JSONArray array = new JSONArray(dataInStringForm);
for (int i=0;i< array.length(); i++)
{
JSONObject json = array.getJsonObject(i);
System.out.println(json.getString("Pref1"));
System.out.println(json.getString("Pref2"));
}
You can parse values from JSONObject and can use getJSONObject(i) in a loop if it's a JSONArray. In your case you should make your preferences a JSONArray
[{"Pref1":"Juan"},{"Pref2":"JuanK"}] so you can get it via getJSONArray() and then parse it better in a loop via getJSONObject(i)
Try this
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
}
}
If it is array then
JSONArray key= (JSONArray) jsonObject.get("yourKey");
Iterator<String> iterator = key.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.
I have this json data below, but I am wondering how I can retrieve the pair of symbol and figure and display it in a Listview.I am only able to retrieve the elements if they are in a JSON Array.Please Help
{ "rates": {
"AED": 3.672626,
"AFN": 48.3775,
"ALL": 110.223333,
"AMD": 409.604993,
"ZAR": 8.416205,
"ZMK": 4954.411262,
"ZWL": 322.355011
}
}
JSONObject jsonResult = new JSONObject(yourString);
JSONObject rates = jsonResult.getJSONObject("rates");
double aed = rates.getDouble("AED");
double afn = rates.getDouble("AFN");
....
try as:
JSONObject jarrau = new JSONObject("Your JSON String");
JSONObject jsonobj = jarrau.getJSONObject("rates");
double dub_AED,dub_AFN, dub_ALL;
//AAED
if(!jsonobj.isNull("AED"))
dub_AED=jsonobj.getDouble("AED");
else
// set default value here
//AFN
if(!jsonobj.isNull("AFN"))
dub_AFN=jsonobj.getDouble("AFN");
else
// set default value here
//ALL
if(!jsonobj.isNull("ALL"))
dub_ALL=jsonobj.getDouble("ALL");
else
// set default value here
// pasre all same as...
As you don't no the keys here in this case we also need to get the keys from the json so in that case we need first keys then we need to get the value of that particular key.
So for that the following is the code :-
String[] sKey,sValue;
JSONObject jobject = new JSONObject(your result);
JSONObject jobj = jobject;
JSONObject jrates = jobj.getJSONObject("rates");
sKey = new String[jrates.length()];
sValue = new String[jrates.length()];
for(int i=0;i<jrates.length();i++){
sKey[i] = (String)keys.next();
sValue[i] = (String)jrates.getString(sKey[i]);
}