I'm trying to create test data with a JSON String, however when I try to convert the string into a JSONArray, the test fails.
String JSONString = "{\"Info\":[{\"area\":301336,\"nativeName\":\"Italia\",\"capital\":\"Rome\",\"demonym\":\"Italian\",\"flag\":\"https://restcountries.eu/data/ita.svg\",\"alpha2Code\":\"IT\",\"languages\":[{\"nativeName\":\"Italiano\",\"iso639_2\":\"ita\",\"name\":\"Italian\",\"iso639_1\":\"it\"}],\"borders\":[\"AUT\",\"FRA\",\"SMR\",\"SVN\",\"CHE\",\"VAT\"],\"subregion\":\"Southern Europe\",\"callingCodes\":[\"39\"],\"regionalBlocs\":[{\"otherNames\":[],\"acronym\":\"EU\",\"name\":\"European Union\",\"otherAcronyms\":[]}],\"gini\":36,\"population\":60665551,\"numericCode\":\"380\",\"alpha3Code\":\"ITA\",\"topLevelDomain\":[\".it\"],\"timezones\":[\"UTC+01:00\"],\"cioc\":\"ITA\",\"translations\":{\"br\":\"Itália\",\"de\":\"Italien\",\"pt\":\"Itália\",\"ja\":\"イタリア\",\"hr\":\"Italija\",\"it\":\"Italia\",\"fa\":\"ایتالیا\",\"fr\":\"Italie\",\"es\":\"Italia\",\"nl\":\"Italië\"},\"name\":\"Italy\",\"altSpellings\":[\"IT\",\"Italian Republic\",\"Repubblica italiana\"],\"region\":\"Europe\",\"latlng\":[42.83333333,12.83333333],\"currencies\":[{\"symbol\":\"\\u20ac\",\"code\":\"EUR\",\"name\":\"Euro\"}]}]}";
JSONArray JSON = new JSONArray(JSONString);
The error is org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
A JSONArray must starts always with [
You must to change your JSONString variable as follow:
Solution 1:
[Info... and so on
Solution 2:
Remove Info because it is typized element of your JSON array
Your string represents a JSON Object, starting with "{".
A JSONArray would begin with a "[".
If you parse the string into a JSONObject first, you should then be able to parse out your JSONArray from the "Info" key.
Just to elaborate on this in your case, something like this:
String JSONString = "{\"Info\":[{\"area\":301336,\"nativeName\":\"Italia\",\"capital\":\"Rome\",\"demonym\":\"Italian\",\"flag\":\"https://restcountries.eu/data/ita.svg\",\"alpha2Code\":\"IT\",\"languages\":[{\"nativeName\":\"Italiano\",\"iso639_2\":\"ita\",\"name\":\"Italian\",\"iso639_1\":\"it\"}],\"borders\":[\"AUT\",\"FRA\",\"SMR\",\"SVN\",\"CHE\",\"VAT\"],\"subregion\":\"Southern Europe\",\"callingCodes\":[\"39\"],\"regionalBlocs\":[{\"otherNames\":[],\"acronym\":\"EU\",\"name\":\"European Union\",\"otherAcronyms\":[]}],\"gini\":36,\"population\":60665551,\"numericCode\":\"380\",\"alpha3Code\":\"ITA\",\"topLevelDomain\":[\".it\"],\"timezones\":[\"UTC+01:00\"],\"cioc\":\"ITA\",\"translations\":{\"br\":\"Itália\",\"de\":\"Italien\",\"pt\":\"Itália\",\"ja\":\"イタリア\",\"hr\":\"Italija\",\"it\":\"Italia\",\"fa\":\"ایتالیا\",\"fr\":\"Italie\",\"es\":\"Italia\",\"nl\":\"Italië\"},\"name\":\"Italy\",\"altSpellings\":[\"IT\",\"Italian Republic\",\"Repubblica italiana\"],\"region\":\"Europe\",\"latlng\":[42.83333333,12.83333333],\"currencies\":[{\"symbol\":\"\\u20ac\",\"code\":\"EUR\",\"name\":\"Euro\"}]}]}";
JSONObject jsonObject = new JSONObject(JSONString);
JSONArray jsonArray = jsonObject.getJSONArray("Info");
Related
Im trying to parse id from following string json:
postResponse :{"success":true,"response_json":"{\"status\":200,\"message\":\"Success\",\"data\":{\"id\":\"f71233gg12\"}}"}
my code looks like below:
System.out.println("postResponse :"+postResponse);
JSONObject responseJson = new JSONObject(postResponse);
JSONObject jsonObjectA = responseJson.getJSONObject("response_json");
JSONObject jsonObjectB = jsonObjectA.getJSONObject("data");
String the_pdf_id = jsonObjectB.get("id").toString();
i keep getting the error:
org.json.JSONException: JSONObject["response_json"] is not a JSONObject.
what could be the reason? any solution for that?
As you can see on your data, the content at key response_json is not a an object, but only a string, another JSON-encoded string
// response_json value is a string
{"success":true,"response_json":"{\"status\":200,\"message\":\"Success\",\"data\":{\"id\":\"f71233gg12\"}}"}
// response_json value is an object
{"success":true,"response_json": {"status":200,"message":"Success","data":{"id":"f71233gg12"}}}
You need a second parse level
JSONObject jsonObjectA = new JSONObject(responseJson.getJSONString("response_json"));
I'm trying to read a JSONObject from within another JSONObject. The first output works, the second, i.e. the JSONObject within, does not. Here I get the following error
org.json.JSONException: JSONObject["Values"] not found.
This is the output of the first object / array
ergebnis: {"Description":"","Objects":[{"RefStr":"76-1044-0","ClassName":"Application","Values":{"providerorg-refstr":"262-462-0",...}]}
This is how I try to get the data:
JSONObject jsonObject = new JSONObject(ergebnis);
System.out.println(jsonObject);
JSONObject inside = jsonObject.getJSONObject("Values");
System.out.println(inside);
Values object is present in Objects. This objects is an array. You can try like below,
JSONObject jsonObject = new JSONObject(json);
System.out.println(jsonObject);
JSONObject jsonObject1= jsonObject.getJSONObject("ergebnis");
System.out.println(jsonObject1);
JSONArray objects = jsonObject1.getJSONArray("Objects");
System.out.println(objects);
JSONObject inside = objects.getJSONObject(0).getJSONObject("Values");
System.out.println(inside);
I have string builder of the form:
[{"abc" : ["something1", "something2"]}, {"def" : ["something3", "something4"]}]
How do I convert it so that I can perform get on the keys? For e.g.: object.get("abc") and i get the list back.
I looked around for solutions:
I tried doing:
JSONObject jsonObject = new JSONObject(sb.toString());
I get the following exception:
exception org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
I then tried taking a sub-string of the Json, like this:
JSONObject jsonObject = new JSONObject(sb.toString().substring(1, sb.toString().length()-1));
which gives back:
jsonObjwct {"Z-DwY2Ul":["Worried Blues","Worried Blues"]}
I get only the first object, i need all of them.
What modifications i can do to get the list back for a specific key?
It is a JSONArray of JSONObject's, so first convert it into JSONArray
JSONArray array = new JSONArray(sb.toString());
And then you can iterate by using for loop
for (int i = 0, size = array.length(); i++) {
JSONObject obj = array.optJSONObject(i); //{"abc" : ["something1", "something2"]}
}
I have a String like this:
{"api_authentication":{"api_response":{"token":"XXXXXXXXXXXXXXXXXXXXXXXXX","firstname":"John","disabled":false,"attempts":0,"id":123,"lastname":"Malkovitch","expire":false,"status":0}}}
I can turn this string into an object:
JSONObject jobj = new JSONObject(response);
But I don't find how to get the token value, I tried creating JSONArrays but i get a not found exception.
You can do it like this ;
final JSONObject api_authentication = jobj.getJSONObject("api_authentication");
final JSONObject api_response = api_authentication.getJSONObject("api_response");
System.out.println(api_response.getString("token"));
if JSON any value in curlybrackets { ... } , this is jsonObject . If values are in [ ... ], this is JsonArray. Also you can get which one is object or array, and get it relevant fields from this. So all of json elements are with curly bracket in your problem. Get it as JsonObject.
this might work by the look of what you have posted. The posted code snippet shows that it is a single JSON object and not a JSONArray.
Hence try the following:
JSONObject jobj = new JSONObject(response);
String newtoken = jobj.getJSONObject("api_authentication").getJSONObject("api_response").getString("token"); //declare the variable `newtoken` somhwere before of a desired type
You could try something like:
Object tokenValue = jobj.getJSONObject("api_authentication").getJSONObject("api_response").get("token");
After that you can cast the object to the desired type or use something like getString(.) straightaway.
I want to get data from php file to Android using JSON. This is my code:
....
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
When I debug the program there is JSONException on this line:
JSONObject last = timeline.getJSONObject(0);
Data is {"a":1,"b":2,"c":3,"d":4,"e":5} and the Exception is:
org.json.JSONException: Value {"d":4,"e":5,"b":2,"c":3,"a":1} of type org.json.JSONObject cannot be converted to JSONArray
The exception message is quite explicit and a look at the JSON syntax diagrams should be illustrative. The JSON string that your code received is:
{"a":1,"b":2,"c":3,"d":4,"e":5}
This string represents an object, not an array. An example of an array would be this:
[1, 2, 3, 4, 5]
or even this:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Note that starting and closing brackets.
I think that you will find that the exception location is slightly misleading. I don't know if it is a result of some sort of lazy initialization or something else, but I believe that the cause is actually this line:
JSONArray timeline = new JSONArray(data);
Since the data string represents a JSON object and not an array, this operation is clearly impossible.
In Json arrays are described using [].
There you define an object with five attributes.
JSONArray timeline = new JSONArray(data);
// change JSONArray to JSONObject
JSONObject timeline = new JSONObject(data);// Like This
Your JSON data is not an array.
Your json response is in Object form, not in Array form.So you have to simply parse your json object. Suppose "data" is the JSONObject tag in response.
Following is the way of Parsing:
HttpEntity e = r.getEntity();
String result = EntityUtils.toString(e);
JSONObject response=new JSOBObject(result);
JSONOBject Data=response.getJSONObject("data");
int a=Data.getInt("a");
int b=Data.getInt("b");
int c=Data.getInt("c");
int d=Data.getInt("d");
int e=Data.getInt("e");
Thanks.