Getting property of an object which has non-fixed keys - android

Assume that I get this JSon Response from webservice:
{
"id":13,
"name":"Alireza",
"required_id":"14",
"all_friends_id_and_name":{
"28":"Hassan",
"21":"Mohammad",
"68":"Ali",
"14":"Taha",
"96":"Darya"
}
}
In this response required_id value specifies that I need a friend name with id 14, so in all_friends_id_and_name object I should get the value of "14" (Taha) and use it in my app.
I'm using retrofit2 and gson libraries.
How to get property of an object which has non-fixed keys?

For Native approach, You can Try with Iterator .
An iterator is an object that enables a programmer to traverse a
container, particularly lists.
"all_friends_id_and_name":{
"28":"Hassan",
"21":"Mohammad",
"68":"Ali",
"14":"Taha",
"96":"Darya"
}
For the above section, Your LOGIC will be
JSONObject jsonData = new JSONObject("Json_response");
Iterator iteratorObj = jsonData .keys();
while (iteratorObj.hasNext())
{
String str_json_Key = (String)iteratorObj.next();
// Print=28,21....96
}

Here is your Json:
{
"id":13,
"name":"Alireza",
"required_id":"14",
"all_friends_id_and_name":{
"28":"Hassan",
"21":"Mohammad",
"68":"Ali",
"14":"Taha",
"96":"Darya"
}
}
Try by doing like this :
try {
JSONObject jsonObject; // it should be your above JsonObject
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
System.out.println("Mykey: " + key + " value: " + jsonObject.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

Android getJSONObject reordered automatic

I use below code :
JSONObject value = ...;
JSONObject stationList = value.getJSONObject("stationList");
Iterator<String> iter = array.keys();
while (iter.hasNext()) {
try {
String key = iter.next();
String val = array.get(key).toString();
Log.i("res", key+"- "+val);
} catch (JSONException e) {
e.printStackTrace();
}
}
My data sort is :
1- name
3- other
2- your
But output is :
1- name
2- your
3- other
I think JSONObject reorder data with integer key.
How I can fix it and read data without reorder?
JSONObjects are similar to map which stores data as a key value pair without maintaining order.

Parse JSON without key

My basic JSON data structure is this:
[
{
"data1":"contents of data1",
"data2":"contents of data 2"
},
{
"data1":"contents of data1",
"data2":"contents of data 2"
}
]
I tried using JSONArray myJson = new JSONArray(json);
but it gives me:
org.json.JSONException: Not a primitive array: class org.json.JSONObject
I am retrieving the JSON through:
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
And convert it to JSONArray using JSONArray myJson = new JSONArray(json);
Thanks!
Iterate your json without key as follows
try {
JSONArray jsonArray = new JSONArray("[{\"data1\":\"contents of data1\",\"data2\":\"contents of data 2\"},{\"data1\":\"contents of data1\",\"data2\":\"contents of data 2\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
System.out.println("Mykey: " + key + " value: " + jsonObject.getString(key));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
The reason of that error might be invalid json.
This is how your data2 key - value pair is
"data2":contents of data 2"
Put the quotes " before contents and use this
"data2":"contents of data 2"
Change all occurences of this error and it should work. Do let me know if it changes anything for you.
In python, If u have json data as
data=[{
"data1":"contents of data1",
"data2":"contents of data 2"
},
{
"data1":"contents of data1",
"data2":"contents of data 2"
}
]
you can access it using:
print "data1:",data[0]["data1"]

How to get a value from JSON Object by a key?

How to get the value by key in a JSON object? I had used following code but it receives "org.json.JSONException". Advance thanks for any help.
String resultJSON = "{Data:[{\"AreaID\":\"13\", \"Phone\":\"654321\", \"RegionName\":\"Sivakasi\"}, {\"AreaID\":\"14\", \"Phone\":\"12345\", \"RegionName\":\"ANJAC\"}]}";
JSONObject jObject = new JSONObject(resultJSON);
JSONObject jsonObject = jObject.getJSONObject("Data");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jsonObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jsonObject.getString(key);
map.put(key,value);
Log.d("Key Value","key: "+key+" Value: "+value);
}
Logcat details
org.json.JSONException: Value [{"AreaID":"13","Phone":"654321","RegionName":"Sivakasi"},{"AreaID":"14","Phone":"12345","RegionName":"ANJAC"}] at Data of type org.json.JSONArray cannot be converted to JSONObject
The structure of your JSON is wrong, you should use a Key for the second JSONObject , like this:
{
Data: {
\"AreaID\": \"13\",
\"Phone\": \"654321\",
\"RegionName\": \"Sivakasi\"
},
\"KEY\": {
\"AreaID\": \"14\",
\"Phone\": \"12345\",
\"RegionName\": \"ANJAC\"
}
}
Or the DATA should be a JSONArray ( surrounded by [] ) like this :
{
Data: [
{
\"AreaID\": \"13\",
\"Phone\": \"654321\",
\"RegionName\": \"Sivakasi\"
},
{
\"AreaID\": \"14\",
\"Phone\": \"12345\",
\"RegionName\": \"ANJAC\"
}
]
}
NOTE : you can check if your json is valid or not here
Personnaly , i prefer the second way ( Using JSONArray) , because the data inside has the same attributes (AreaID, Phone, REgionName). To parse data in this case , your code should be someting like this :
String resultJSON = "{Data:[{\"AreaID\":\"13\", \"Phone\":\"654321\", \"RegionName\":\"Sivakasi\"}, {\"AreaID\":\"14\", \"Phone\":\"12345\", \"RegionName\":\"ANJAC\"}]}";
JSONObject jsonRoot = new JSONObject(resultJSON);
JSONArray jsonData = jsonRoot.getJSONArray("Data");
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonOBject = jsonData.getJSONObject(i);
Log.d(TAG, "json ("+i+") = "+jsonOBject.toString());
// do what you want with your JSONObject , i.e :add it to an ArrayList of paresed result
String areaID = jsonOBject.getString("AreaID");
int phoneNumber = jsonOBject.getInt("Phone");
String regionName = jsonOBject.getString("RegionName");
}
This is invalid JSON format. Before you convert your string to JSON object format, be sure about it's valid or not.
Please check validity of your JSON.
Hope it may help.

data from a jsonobject in android

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.

Json Without Key to Parse in Android

I have this below Json which I'm getting from a .Net Web service:
[["Developer","test","developer#test.com"]]
I checked with jsonlint validator and It shows above json fine.
Because it is not having any key I don't know how to parse it in Android.
Can someone please help me how to parse this json without key.
If it had keys, I would have tried this:
{"first":"somevalue","last":"someothervalue"} // Json response
JSONObject json_obj = new JSONObject(resp); //response is the json array
String first = json_obj.getString("first");
String last = json_obj.getString("last");
String test = "Hello! " + first + " " + last;
Hope someone helps :)
Regards,
Praveen
MY SOLUTION
JSONArray respo = new JSONArray(resp); //resp is Json Array
respo = respo.getJSONArray(0);
String test = respo.getString(2);
test = "Your Email Address is " + test;
in Android (Java) parsing this line looks like:
String jsonString="[[\"Developer\",\"test\",\"developer#test.com\"]]";
try {
JSONArray jsonArray=new JSONArray(jsonString);
JSONArray jsonArray2=jsonArray.getJSONArray(0);
for (int i = 0; i < jsonArray2.length(); i++) {
String valueString=jsonArray2.getString(i);
Log.e("json", i+"="+valueString);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use JSONArray instead of JSONObject. Then use the getJSONArray() function to get the array inside the array. After that you can access all values with their index and getString().

Categories

Resources