converting from String to JSONArray or JSONObject in Java - java

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.

Related

Accessing Nested Elements of JSON in Java

I have a java project in which I take a JSON and read its contents. I'm using org.json libraries and I would like to iterate through JSONObjects which are nested in a JSONArray, which is nested in a JSONObject. I keep getting this error though: JSONArray initial value should be a string or collection or array. I'm specifically getting the JSON from a web source, but here is an example of one: http://jsonblob.com/1062033947625799680
I'm particularly concerned about the fact that each player profile is unnamed, but there may be a simple fix for that.
I'd like to get access to each player profile and here is what I have that is causing an error:
import org.json.*;
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int z = 1; i<data.length(); i++)
{
JSONObject ply = new JSONObject(data.getJSONObject(z));
System.out.println(ply.toString());
}
I have a feeling I just don't fully understand the terminology of JSON and/or the library that I'm using, but any help is appreciated.
Try this instead:
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int i = 0; i<data.length(); i++) {
JSONObject ply = data.getJSONObject(i);
System.out.println(ply.toString());
}
It turns out I just have to access the particular element in one line:
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = JSON.getJSONArray("data");
for(int z = 0; z<data.length(); z++)
{
//JSONObject ply = new JSONObject(data.getJSONObject(z));
String name = data.getJSONObject(z).getString("skaterFullName");
System.out.println(name);
}

Get array with json object out of a string

I have a java spring boot project that makes an REST API call and one element of the returned json is as follows:
"args": "[[\"element_1\"],[\"element_2\"],[\"{\\\"payload\\\":\\\"{\\\"Header\\\": \\\"Header_title\\\", \\\"Content\\\": \\\"Content of the payload\\\"}\\\"}\"]]"
My objective is to get the JsonObject "payload". I can get the string using
JsonObject argString = (JsonObject) jsonParser.parse(originalJsonObject.get("args").toString());
(using the package com.google.gson.JsonObject) but I can't get the two-dimensional array out of the string.
The part of data that you've included actually is a key args with a string value [[\"element_1\"],[\"element_2\"],[\"{\\\"payload\\\":\\\"{\\\"Header\\\": \\\"Header_title\\\", \\\"Content\\\": \\\"Content of the payload\\\"}\\\"}\"]]. So it is correct that you cannot get these contents decoded through a method on the existing Json, but you can take the string and parse it to a json array as follows:
JsonElement jsonElem = new JsonParser().parse(argString);
JsonArray jsonArray = jsonElem.getAsJsonArray();
for(int i = 0; i < jsonArray.size(); i++) {
System.out.println(jsonArray.get(i));
}

How to extract json Objects from String Builder?

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"]}
}

Android: JSONObject cannot be converted to JSONArray

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.

org.json.JSONException: "JSON object not found in JSON 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
}

Categories