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.
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");
}
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"]
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");
Hello i am getting error in the follwing code as- "Value at reachus of type java.lang.String cannot be converted to JSONObject"..I am getting values for all other Json object but getting error at reachus object..how to convert java.lang.String to the JsonObject?please give the solution..Thanks
JSONObject jObj = new JSONObject(Constants.sercall.response_str);
JSONObject jObj2 = new JSONObject;
jObj2 = jObj.getJSONObject("value");
JSONObject jObj6=new JSONObject;
jObj6=jObj2.getJSONObject("reachus");
if (jObj6.has("Email")) {
activitycontactinfo = jObj6.getString("Email");
activitycontactinfo = URLDecoder.decode(activitycontactinfo);
activitycontactinfo= activitycontactinfo.replace("%20", " ");
activitycontactinfo = Constants.convertToUpperCase(activitycontactinfo);
}
Here is my Json:
{"value":{
"classdetails":{},
"other_activities_details":"",
"activitydetails":{},
"youlearn":"",
"reachus":{
"Email":[
"varsha.b%40wiztango.com"
],
"facebook":"http%253A%252F%252Fwww.facebook.com%252FVarsha%2520Borhade",
"website":"http%253A%252F%252Fwww.wiztango.com",
"linkedin":"http%253A%252F%252Fwww.linkedin.com%252Fborhadevarsha",
"twitter":"http%253A%252F%252Fwww.twitter.com%252Fvarshaborhade",
"phone number":[
{
"value":"678698",
"meta":"varsha"
}
]
},
"spons_speak_host":"",
"categories":"",
"display_blocks":[],
"display_user_information":[],
"display_content_information":[],
"display_published_contents":[],
"faculty_published_contents":[],
"open_url_enrollment_users_list":"0",
"total_participants":[],
"display_agenda_information":[],
"faculty_published_agenda":[],
"display_published_agenda_ids":[]
}
}
This code enables you to access the 'reachus' field and email:--
Use this code:--
JSONObject jsonObject = new JSONObject(s);
JSONObject reachusJson = jsonObject.getJSONObject("value")
.getJSONObject("reachus");
JSONArray emailArray = reachusJson.getJSONArray("Email");
Log.e("email ", emailArray.getString(0));
First, please use more meaningful names for your variables, then look at the structure of your JSON, it's:
JSONObject (main) -> JSONObject (value) -> JSONObject (reachus) -> JSONArray (Email) -> String
So:
Get your JSOBObject
JSONObject json = new JSONObject(Constants.sercall.response_str);
Get JSONObject for "value":
JSONObject valueJson = json.getJSONObject("value");
Get JSONObject for "reachus":
JSONObject reachusJson = json.getJSONObject("reachus");
Because "Email" is JSONArray, first get JSONArray, then get the first string (assuming there is one):
if (reachusJson.has("Email")) {
JSONArray emailJsonArray = reachusJson.getJSONArray("Email");
//rest of your code
activitycontactinfo = emailJsonArray.getString(0);
activitycontactinfo = URLDecoder.decode(activitycontactinfo);
activitycontactinfo = activitycontactinfo.replace("%20", " ");
activitycontactinfo = Constants.convertToUpperCase(activitycontactinfo);
}
You might want to add some checks in case Email array is empty.
it gives me the error log : " org.json.JSONException: No value for tableData"
try {
JSONObject mainJson22 = new JSONObject(reply);
JSONObject jsonResult = mainJson22.getJSONObject("UserListByBusinessAreaContextResult");
JSONArray jsonArray22 = jsonResult.getJSONArray("tableData");
// JSONArray jsonArray22 = mainJson22.getJSONArray("UserListByBusinessAreaContextResult"); // JSONArray jsonArray22 = jsonResult.getJSONArray("tableData"); Log.i("mainjson234","" + jsonArray22);
for (int i2 = 0; i2 < jsonArray22.length(); i2++) {
JSONObject objJson22 = jsonArray22.getJSONObject(i2);
the error is on line : `"JSONArray jsonArray22 = jsonResult.getJSONArray("tableData");"
heres the json:
{
"UserListByBusinessAreaContextResult": "{\"tableData\":[{\"UserID\":30,\"Username\":\"Teste\",\"Name\":\"Teste\"}]}"
}
The object UserListByBusinessAreaContextResult contains a string. This string is:
"{\"tableData\":[{\"UserID\":30,\"Username\":\"Teste\",\"Name\":\"Teste\"}]}"
Do you notice the quotes? The problem is, that your WCF service returns a JSON string, not an object. So either you will have to change the WCF service to deliver an object instead, or parse that string again. Like this (not tested):
JSONObject mainJson22 = new JSONObject(reply);
JSONObject tableData = new JSONObject(
mainJson22.getString("UserListByBusinessAreaContextResult"));