JSONObject create iterator with Integer - android

I want to iterate a JSONObject by using the method keys(). The problem is that one of the key is an Integer.
Iterator it = json.getJSONObject("body").keys();
The keys() method only creates an iterator from String values and I get an exception when one of the keys is an Integer. What can I do to solve this?

please read following example
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
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);
}

JSON object members are key-value pairs where the key is always a string (ref). If it's a number literal, then the JSON is invalid. You should fix whatever is producing that invalid JSON.

Related

Android studio: How to receive Json Volley with different objects

According to this json file I want to receive data1 , xyz, abc object and their sub objects and show it in recyclerview.But I am receiving only data1 and their key-value pairs(index1 and name). I am using library Volley.
Can someone help me how to recive xyz and abc ?
{
"Data1":{
"index1":"4",
"name":"dan"
},
"xyz":{
"index1":"2",
"name":"jimi"
}
"abc":{
"index1":"5",
"name":"jordan"
}
}
JSONObject jsonObject = response.getJSONObject("Data1");
getset1.seti(jsonObject.getString("index1"));
getset1.setn(jsonObject.getString("name"));
Try this
JSONObject jsonobject=new JSONobject("");
for (int i=0;i<jsonobject.length();i++){
JSONObject jsonObject1=jsonobject.getJSONObject(i);
);
You have to use loop.As this is not an array so u have to fetch the all keys using iterator and then loop among them try this
Iterator<String> keys = json.keys();
while (keys.hasNext())
{
// Get the key
String key = keys.next();
// Get the value
JSONObject value = json.getJSONObject(key);
// parse inner string from value
}

Retrieve Data from Firebase with random key

I'd like to retrieve the value of each key from my json file cardInfo
"cardInfo" : {
"-KF3fzOc3e68jRpCkLRb" : 6869098993309203,
"-KF3g0fQUJHcexwAFzxz" : 6764366404306628,
"-KF3hHOdj-siBxLMNgLa" : 4368998299921475,
"-KF3hLzxQsmTP9MJ6iVe" : 8779395075647930,
"-KF3hM3_mOn_VoN9-bW6" : 6867202628499185,}
But since i'm using Push method for saving these random numbers , which method shall i use to get access to those values through these random keys to save them into some TextViews.
Thanks :)
You can use public Iterator<String> keys()
Returns an iterator of the String names in this object. The returned
iterator supports remove, which will remove the corresponding mapping
from this object. If this object is modified after the iterator is
returned, the iterator's behavior is undefined. The order of the keys
is undefined.
Example:
JSONObject jObj = new JSONObject(response);
JSONObject json = jObj.getJSONObject("cardInfo");
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
Log.e("JSON-ERROR",e.toString());
}
}

Parsing JsonObject's fields regardless of their name

I've been looking for this for a while now, but couldn't find it anywhere in SO or in the docs.
I am using Gson to parse a json file, and suppose the file is:
{
"animal":"cat",
"paws":"4",
"eyes":"2"
}
Now, since all the fields are strings, I want to parse it as an array of strings, I want something like:
{"cat","4","2"}
And I would like to parse the JsonObject regardless of the name of its tags, and that's where the problem lies. I can garantee the json will contain only strings, but I have no clue of what the fields are going to be named.
Anyone ever faced this problem ? Any help is much appreciated, and any research direction also.
Edit
From the anwers, I managed to do it like this:
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
// do your stuff here
}
as explained in this answer
JSONObject has the keys() method that returns an Iterator<String>. Through the iterator you can retrieve the value associated with each key. Here the documentation
EDIT:
Since you are using GSON , you can retrieve the keys through the method entrySet()
You should use Iterator, which you can get by calling .keys() on your JSONObject. I think something like that should work (using org.json library):
String[] output = new String[jsonObject.length()];
Iterator iterator = jsonObject.keys();
int i = 0;
while (iterator.hasNext()){
output[i++] = jsonObject.optString((String) iterator.next());
}
EDIT Ok, in case of GSON it will be like this:
Set<Map.Entry<String, JsonElement>> set = jsonObject.entrySet();
String[] out = new String[set.size()];
int i = 0;
for (Map.Entry<String, JsonElement> x : set){
out[i++] = x.getValue().toString();
}
If you are using gson then simple solution is :
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(YOUR_JSON_STRING, mapType);
// get only values from map
Collection<String> values = map.values();
for (String string : values) {
// do your stuff here
}
result values collection contains
[cat, 4, 2]
JSONObject jsonObject = new JSONObject(parentJson.getJSONObject("objectname")
.toString());
Iterator<?> iter = jsonObject.keys();
while (iter.hasNext()) {
String key =(String) iter.next();
String value = jsonObject.getString(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");

Get JSONObject by ID from another JSONObject - Android

I have a little issue with parsing JSON String which I get from a web server. So my JSON looks something like this :
{
..........
"statistics":{
"660":{
"param_id":660,
"cat_id":2,
"param_title":"Number",
"param_value":"26",
"value_type":"singleline",
"elem_order":"1"}
,
"662":{
"param_id":662,
"cat_id":2,
"param_title":"Name",
"param_value":"Dani",
"value_type":"singleline",
"elem_order":"2"
}
// --||--
}
}
So I get a JSONObject statisics and I want to get JSONObjects from statistics, but the problem is that their name is different everytime.So I can't just do json.getJSONObject("660");. So any suggestions how can I do that?
You can do something like this :
if(jsonObj.has("statistics")){
Iterator<Object> keys = stats.keys();
while(keys.hasNext()){
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = stats.getJSONObject(key);
// get JSON
}// end while
}//end if
use JSONObject.keys() to get key iterator, then getJsonObject( key) to get object.
Try below code-
JSONArray nameArray = statisics.names();
JSONArray valArray = statisics.toJSONArray(nameArray);
where names() method returns array of names and it is stored in nameArray and valArray contains array of values corresponding to valArray.
You can iterate using for loop over these array to get values.
use like this
JSONObject jsonOnb = json.getJSONObject("statistics") ;
JSONObject pagesObj = jsonOnb.getJSONObject(jsonOnb.names().getString(0));
Log.i("pageid", "pageid= " +pagesObj.get("param_id"));
Log.i("title", "title= " +pagesObj.get("cat_id"));
..............

Categories

Resources