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");
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'm trying to use the JSON library to consume twitter information from the get search feature. I'm getting the error:
A JSONArray text must start with '[' at 1 [character 2 line 1]
So it's basically in the wrong form. Some people are saying this needs to be an object but everytime I call the constructor it says that it can't take a String as input. How do I get this string into the form of a JSONArray so that I can access it's elements.
Here is my code:
URL twitterSource = new URL("http://search.twitter.com/search.json?q=google");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse JSON
System.out.println(urlContents);
JSONArray jsonArray = new JSONArray(urlContents);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
my print statement shows the string contains:
{"completed_in":0.318,"max_id":144850937012428800,"max_id_str":"144850937012428800","next_page":"?page=2.....................
This is a string in the form of a JSON object but it is not actually an object. It's still a string. I'm printing a String. HOw can I get this into an Object or better yet a JSONArray so that I can actually access its elements.
That's a JSON object, not an array.
A very simple JSON like this (response.getBody().toString()):
{"per_page":50,"total":93,"last_page":2,"stars":[]}
Has some problems when I want to parse it:
JSONObject object = new JSONObject(response.getBody()); // no error
System.out.println(object.getJSONObject("total")); // not found
org.json.JSONException: JSONObject["total"] not found.
Other properties cannot be parsed either:
JSONArray startups = object.getJSONArray("stars");
org.json.JSONException: JSONObject["stars"] not found.
The key is to hold the value of response.getBody()
String json = response.getBody().toString();
Inside object total is not JSONObject it is an Int value, that's why you code crashing.
So use this
System.out.println(String.valueOf(object.getInt("total")));
instead of
System.out.println(object.getJSONObject("total"));
String json = "{\"per_page\":50,\"total\":93,\"last_page\":2,\"stars\":[]}":
JSONObject jsonObject = new JSONObject (json);
JSONArray jsonArray = jsonObect.getJSONArray("stars");
int perPage = jsonObject.getInt("per_page");
try like this...
In addition to earlier answer, to parse array, use getJSONArray as
JSONArray ja = jsonObj.getJSONArray("stars");
You can loop-over the array as:
for(int j=0; j<ja.length(); j++) {
JSONObject json = ja.getJSONObject(j);
// do same as before for string, int or other data types
}