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"]
Related
I am trying to parse json but it gives me exception.
I hardcoded expected json as String like this
String stringJSON="[{\"value1\":\"ABC567123\",\"end_at\":\"08/28/2014 09:10:00\",\"start_at\":\"04/25/2016 09:20:00\"}]";
Valid json is like this
[
{
"value1": "ABC567123",
"end_at": "08/28/2014 09:10:00",
"start_at": "04/25/2016 09:20:00"
}
]
Now I am trying to parse json like below and getting exception.
JSONObject responseObJ;
try {
responseObJ= new JSONObject(stringJSON); //error here
if(responseObJ!=null){
//do something
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Please suggest what to do?
//hard coded it for temporary - json result is expected to exact same
stringJSON is contains JSONArray instead of JSONObject as root element in JSON String.
Either remove [] from start and end of String according to current code or if multiple JSONObject's is available in JSONArray then get JSONArray from stringJSON :
JSONArray responseObJ= new JSONArray(stringJSON);
[ ] they show that it has an array of objects in it so you can retrieve it like this
JSONArray jsonArray= new JSONArray(stringJSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jObject.getJSONObject(i);
// here you can get the values of objects stored in the jsonObject
}
In your case you have only one object so you don't have to use loop instead you can get it like this
JSONArray jsonArray= new JSONArray(stringJSON);
JSONObject jsonObject = jObject.getJSONObject(0);
yes as you said its valid json but its JsonArray not JsonObject.
Just remove [] from start and end.
your string should be
String stringJSON="{\"value1\":\"ABC567123\",\"end_at\":\"08/28/2014 09:10:00\",\"start_at\":\"04/25/2016 09:20:00\"}";
or if you want to work with current string then use JsonArray instead of JsonObject
JSONArray responseObJ= new JSONArray(stringJSON);
Can you try Deserialize method of ScriptSerializer class? Like:
var scriptSerializer = new JavaScriptSerializer();
var obj = scriptSerializer.Deserialize<Object>(str);
I have 2 links; which gives json data. I am trying to get the values from the urls from the same activity in android using asynTask. did the coding till converting the data to string(stored it in jsonStr1). But now comes the problem. Because,among the 2 urls:
one starts with JSON object-
{ "contacts": [ {"id": "c200", "name": "Ravi Tamada" },
{ "id": "c201", "name": "Johnny Depp" }
]
}
another start with JSON array-
[{"appeId":"1","survId":"1"},
{"appeId":"2","survId":"32"}
]
Now how am i going to give a condition for them whether to know its a JSON array or Object? JSON array are object that i know but cant find how to separate them. i have tried the below:
JSONObject jsonObj = new JSONObject(jsonStr1);
if(jsonObj instanceof JSONArray){}
but if condition is showing error- incompatible conditional operand types JSONObject and JSONArray
You can simply use startsWith for String to check where the String starts with { or [
boolean isJsonArray = jsonResponse.startsWith("[");
if(isJsonArray){
// Its a json array
}
else{
// Its a json object
}
You can use JSONTokener class for that, here is a sample code for that.
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject){
JSONObject result = new JSONObject(response);
}
else if (json instanceof JSONArray){
JSONArray resultArray = new JSONArray(response);
}
make jsonobject and call which place u want to calling
jsonobject = JSONfunctions
.getJSONfromURL("http://ampndesigntest.com/androidapi/CURRENTPROJECTDATA/textfiles/hotels");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag"));
// map.put("latlongitude", jsonobject.getString("latlongitude"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
You could use the method has(String) to check if the JSONObject contains or not the key contacts.
if(jsonOjbect.has("contacts") {
...
}
else {
...
}
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.
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.
I am new to the android development. i am having the following android code to call the json
try {
JSONObject jsonObject = new JSONObject(result);
//JSONObject object = jsonObject.getJSONObject("CUSTOMER_ID");
JSONArray jArray = new JSONArray(CUSTOMER_ID);
returnUsername1 = jArray.getInt("CUSTOMER_ID");
Toast.makeText(getApplicationContext(), ""+returnUsername1,Toast.LENGTH_LONG).show();
for (int i = 0; i < jArray.length(); i++) {
}
My JSON format is like [[{"0":"1","CUSTOMER_ID":"1"}]].
i refer some json format it should like [{"0":"1","sno":"1"}] i can understand this.But mine is different from this.
how can i call the customer_id using the above code.anyone can suggest a solution.
What you have is a Json Array
JSONArray jsonarray = new JSONArray(result); // result is a Array
[ represents json array node
{ represents json object node
Your Json. Do you need a Json array twice?
[ // array
[ //array
{ // object
"0": "1",
"CUSTOMER_ID": "1"
}
]
]
Parsing
JSONArray jsonArray = new JSONArray(result);
JSONArray ja= (JSONArray) jsonArray.get(0);
JSONObject jb = (JSONObject) ja.get(0);
String firstvalue = jb.getString("0");
String secondvalue = jb.getString("CUSTOMER_ID");
Log.i("first value is",firstvalue);
Log.i("second value is",secondvalue);
LogCat
07-22 14:37:02.990: I/first value is(6041): 1
07-22 14:37:03.048: I/second value is(6041): 1
Generally, to get a JSONObject from a JSONArray:
JSONObject jsonObject = jsonArray.getJSONObject(0); //0 -> first object
And then
int userID = jsonObject.getInt("CUSTOMER_ID");
CUSTOMER_ID is not considered a JSONObject in this case. If jsonObject is what you think it is, then you should be able to access it with jsonObject.getString("CUSTOMER_ID")
if you have any problems regarding to your JSON format first validate it through this site
http://jsonlint.com/
then for parsing
JSONObject jsonObject = new JSONObject(result);
// since your value for CUSTOMER_ID in your json text is string then you should get it as
// string and then convert to an int
returnUsername1 = Integer.parseInt(jsonObject.getString("CUSTOMER_ID"));
Try this
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray =json.getJSONArray("enterjsonarraynamehere");
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String cust= oneObject.getString("CUSTOMER_ID");
} catch (JSONException e) {
// Oops something went wrong
}
}
Im assuming your json is something like this
<somecode>
{
"enterjsonarraynamehere": [
{ "0":"1",
"CUSTOMER_ID":"1"
},
{ "0":"2",
"CUSTOMER_ID":"2"
}
],
"count": 2
}
<somecode>