Iterating through JSONObject - android

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());
}

Related

How can I put JSON return in an array?

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");
}

Get first object in the JSONObject using int variable

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");

Android parsing a JSON message

I'm trying to parse the following JSON string
String _message = "GetXTRONResult: \"[{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]\"";
JSONObject jsonObj = new JSONObject(_message);
//Try to convert to array
JSONArray array = jsonObj.getJSONArray("GetXTRONResult"); //FAILS !
What is the best way to parse the above please?
UPDATE:
This is what the value is during debugging:
{"GetXTRONResult":"[{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]"}
org.json.JSONException: Value .... at GetXTRONResultof type java.lang.String cannot be converted to JSONArray
SOLUTION THAT WORKED FOR ME:
I had to use the iterator as follows:
ArrayList list = new ArrayList();
JSONObject jsonObj = new JSONObject(_message);
Iterator<?> keys = jsonObj.keys();
if (keys.hasNext()) {
JSONArray array = new JSONArray((String) jsonObj.get((String) keys.next()));
for (int i = 0; i < array.length(); ++i) {
list.add(array.getJSONObject(i).getString("xtron").toString());
}
You have some errors in your json string, like "[.
You can't use quotes that wrap your list.
This one should work:
String _message = "{\"GetXTRONResult\": [{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]}";
JSONObject jsonObj = new JSONObject(_message);
//Try to convert to array
JSONArray array = jsonObj.getJSONArray("GetXTRONResult");
System.out.println(array);
Output: [{"xtron":"Acub1"},{"xtron":"Acub2"},{"xtron":"Acub3A"}]
To avoid your confusion when making JSON in java/android
you could use single quote (') instead of double quote (") for JSON inside Java Code
For example:
from
"{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}"
to be something like this
"{'xtron':'Acub1'},{'xtron':'Acub2'},{'xtron':'Acub3A'}"
I think this is what you're looking for:
JSONObject rootObj = new JSONObject(jsonString);
String theArrayJSON = rootObj.getJSONArray("GetXTRONResult");
JSONObject theArray = new JSONObject(theArrayJSON);

Json parser in android

I have below string. i want to get jsonarray from this string keyword like id, title and so on.
Json_obj = new JSONObject(result);
vid = Json_obj.getJSONArray("id");
//vcatid= Json_obj.getJSONArray("title");
vtitle= Json_obj.getJSONArray("title");
vdesc= Json_obj.getJSONArray("content");
//vimgurl= Json_obj.getJSONArray("vimgurl");
vidlike= Json_obj.getJSONArray("likes");
vidview= Json_obj.getJSONArray("views");
//vidfblike= Json_obj.getJSONArray("vidfblike");
//vidtwlike= Json_obj.getJSONArray("vidtwlike");
storagepath= Json_obj.getJSONArray("url");
Log.i("json_Video_id vid.length() ",
"%%%%%%%%%%%%%%%%%%%%%% "
+ vid.length());
[{"id":"39","title":"\u0627\u0644\u0631\u0651\u0628\u0627 ","content":"\r\n\u0627\u0639\u0644\u0627\u0646 \u0641\u064a \u0627\u0644\u062a\u062d\u0630\u064a\u0631 \u0645\u0646 \u0645\u0634\u0643\u0644\u0627\u062a \u0627\u0644\u0631\u0628\u0627 \u0639\u0644\u0649 \u0627\u0644\u0639\u0627\u0644\u0645 \u0623\u062c\u0645\u0639.\r\n\u0641\u064a\u062f\u064a\u0648 \u0643\u0644\u064a\u0628 \u0628\u062f\u0642\u0629 \u0639\u0627\u0644\u064a\u0629 HD\r\n\u0645\u0646\u062a\u062c \u0645\u0646\u0641\u0630 \u0648\u0644\u064a\u062f \u0627\u0644\u0633\u0646\u062f New View","url":"http:\/\/www.youtube.com\/embed\/L9aPhl6eST0","views":"264","likes":"6"},{"id":"44","title":"\u062e\u064a\u0648\u0637 \u0627\u0644\u0646\u0648\u0631 \u0645\u062d\u0645\u062f \u0627\u0644\u0639\u0632\u0627\u0648\u064a ","content":"\u0641\u064a\u062f\u064a\u0648 \u0643\u0644\u064a\u0628 \u0644\u0635\u0627\u0644\u062d \u0645\u0634\u0631\u0648\u0639 \u0627\u0644\u0639\u0634\u0631 \u0627\u0644\u0623\u062e\u064a\u0631\r\n\u0643\u0644\u0645\u0627\u062a \u0633\u0644\u0637\u0627\u0646 \u0627\u0644\u0633\u0628\u0647\u0627\u0646\r\n\u0623\u062f\u0627\u0621 \u0648\u0644\u062d\u0646 \u0645\u062d\u0645\u062f \u0627\u0644\u0639\u0632\u0627\u0648\u064a\r\n\u0627\u062e\u0631\u0627\u062c \u0645\u062d\u0645\u062f \u062e\u0627\u0637\u0631\r\n","url":"http:\/\/www.youtube.com\/embed\/sOoP6SW-wuo","views":"1156","likes":"10"},{"id":"47","title":"\u062a\u0643\u0627\u0641\u0644 \u0646\u0627\u0635\u0631 \u0627\u0644\u0633\u0639\u064a\u062f ","content":"\r\n\u0644\u0644\u0641\u0642\u062f\u0650 \u0623\u0648\u062c\u0627\u0639\u064c \u062a\u062e\u062a\u0628\u0626 \u0628\u064a\u0646 \u062c\u062f\u0631\u0627\u0646 \u0627\u0644\u0623\u0644\u0645 \u0648 \u0623\u0633\u062a\u0627\u0631\u0650 \u0627\u0644\u0635\u0645\u062a .. \u0648 \u062f\u0645\u0648\u0639 \u062a\u0628\u0644\u0650\u0651\u0644\u064f \u0635\u062f\u0631\u0627\u064b \u064a\u0636\u062c\u064f\u0651 \u0628\u0627\u0644\u062d\u0646\u064a\u0646 ..\r\n\r\n\u0647\u064a \u0631\u062d\u0644\u0629\u064c \u062a\u0644\u062d\u0641\u062a\u0652 \u0628\u0623\u062d\u0632\u0627\u0646\u0650 \u0627\u0644\u063a\u0631\u0648\u0628 ..\r\n\u0648 \u062d\u0643\u0627\u064a\u0629\u064c \u0643\u064f\u062a\u0628\u062a\u0652 \u0639\u0644\u0649 \u062c\u062f\u0627\u0631\u0650 \u0627\u0644\u0642\u064e\u062f\u064e\u0631 .. \u0623\u0628\u0637\u0627\u0644\u0647\u0627 \u0623\u064a\u062a\u0627\u0645 .. \u0642\u062f \u063a\u0641\u0644 \u0639\u0646\u0647\u0645 \u0627\u0644\u0643\u062b\u064a\u064a\u064a\u064a\u0631 \u0645\u0646 \u0627\u0644\u0623\u0646\u0627\u0645 !\r\n\r\n\u0642\u062f \u0631\u0633\u0645\u0648\u0627 \u0623\u062d\u0644\u0627\u0645\u064e \u0627\u0644\u0643\u0628\u0627\u0631\u0650 \u0628\u0623\u064a\u062f\u064a\u0647\u0645 \u0627\u0644\u0645\u062a\u0639\u0628\u0629 .. \u0641\u0627\u0628\u062a\u0633\u0645\u0648\u0627 \u0628\u0634\u0641\u0627\u0647\u064d \u0634\u0627\u062d\u0628\u0629 ..\r\n\u062a\u063a\u0634\u0627\u0647\u0645 \u0645\u0633\u0627\u0621\u0627\u062a\u064c \u062a\u0628\u0643\u064a \u0627\u0646\u0643\u0633\u0627\u0631 \u0627\u0644\u062d\u064a\u0627\u0629 ..\r\n\u0648 \u064a\u0636\u0645\u0647\u0645 \u0628\u064a\u062a\u064c \u0634\u0647\u0650\u062f\u064e \u062a\u0641\u0627\u0635\u064a\u0644 \u0627\u0644\u0645\u0623\u0633\u0627\u0629 ..\r\n\u0648 \u062d\u0641\u0650\u0638\u064e \u0623\u0633\u0631\u0627\u0631 \u0627\u0644\u0643\u0631\u0627\u0645\u0629 !\r\n\r\n\r\n\u0641\u064a\u062f\u064a\u0648 \u0643\u0644\u064a\u0628 \u0633\u064a\u0646\u0645\u0627\u0626\u064a \u0645\u0646 \u0625\u0646\u062a\u0627\u062c \u0648\u0625\u0634\u0631\u0627\u0641 \u062c\u0645\u0639\u064a\u0629 \u062a\u0643\u0627\u0641\u0644 \u0627\u0644\u062e\u064a\u0631\u064a\u0629 \u0628\u0627\u0644\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0646\u0648\u0631\u0629 takaful.sa","url":"http:\/\/www.youtube.com\/embed\/YyYmy79pKfs","views":"181736","likes":"1141"}]
This is how you parse JSON Array
JsonElement json = new JsonParser().parse(response);
JsonArray array = json.getAsJsonArray();
Iterator iterator = array.iterator();
List<CustomClass> obj_list = new ArrayList<CustomClass>();
while (iterator.hasNext()) {
JsonElement json2 = (JsonElement) iterator.next();
Gson gson = new Gson();
CustomClass obj = gson.fromJson(json2, CustomClass.class);
obj_list.add(obj);
}
Here, CustomClass will be a class with the properties you want. That means the properties you get in Array, e.g. id, title, content, likes, views, url.
Hope it helps.
The outmost container of your JSON data is an array and not an object (it start and ends with square brackets). Thus, you need to use the class JSONArray and then iterate over all elements of the array:
String jsonString = ...
JSONArray arr = new JSONArray(jsonString);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
String id = obj.getString("id");
String title = obj.getString("title");
...
}

How to retrieve json object elements that are not in an array?

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]);
}

Categories

Resources