Assistance parsing with gson (google json) - java

I have some JSON. With GSON, it always throws an error
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Object:
[["Rank","Team","Qual Avg","Auto","Container","Coopertition","Litter","Tote","Played"],[1,1730,126.3,160,488,160,137,318,10],[2,1806,96.799999999999997,20,516,80,62,344,10],[3,4522,79.799999999999997,0,404,40,64,308,10],[4,2410,79.0,26,264,160,104,242,10],[5,1329,77.099999999999994,26,220,240,121,188,10],[6,1939,65.0,28,204,80,150,194,10],[7,2457,64.799999999999997,0,328,0,100,232,10],[8,1785,61.200000000000003,20,148,120,142,188,10],[9,4646,59.5,0,200,120,81,206,10],[10,1723,58.600000000000001,24,164,80,156,168,10],[11,5476,54.899999999999999,20,160,120,103,152,10],[12,5126,54.600000000000001,0,168,120,102,168,10],[13,1763,54.100000000000001,12,164,160,67,168,10],[14,1775,54.0,0,148,120,112,178,10],[15,4809,53.100000000000001,24,148,80,117,182,10],[16,1810,52.700000000000003,0,188,80,53,206,10],[17,5013,52.399999999999999,0,148,80,110,192,10],[18,1777,52.299999999999997,8,116,200,97,126,10],[19,1825,52.0,20,200,40,94,178,10],[20,1764,51.5,34,204,0,127,156,10],[21,2164,51.100000000000001,0,160,80,71,212,10],[22,1737,50.399999999999999,10,132,120,74,172,10],[23,3528,50.100000000000001,0,156,80,81,200,10],[24,938,49.100000000000001,20,188,40,115,152,10],[25,5098,48.799999999999997,4,180,80,64,178,10],[26,1987,47.700000000000003,20,76,80,49,258,10],[27,2167,47.5,28,128,80,81,186,10],[28,2335,47.299999999999997,0,128,40,127,178,10],[29,1288,44.600000000000001,12,128,40,68,204,10],[30,5119,44.200000000000003,26,108,80,108,134,10],[31,1802,43.899999999999999,6,136,80,35,188,10],[32,5268,43.600000000000001,26,92,40,110,174,10],[33,4959,43.0,4,136,80,86,140,10],[34,1982,42.799999999999997,12,116,80,88,162,10],[35,2357,41.399999999999999,0,112,120,76,160,10],[36,4455,40.700000000000003,26,168,0,87,132,10],[37,2874,40.5,0,104,80,93,146,10],[38,2560,40.200000000000003,6,132,40,134,96,10],[39,937,39.899999999999999,0,112,80,69,150,10],[40,2353,39.700000000000003,6,100,80,69,178,10],[41,1997,36.0,0,84,120,38,130,10],[42,5082,35.600000000000001,20,64,40,124,114,10],[43,1710,35.299999999999997,0,76,40,57,192,10],[44,3485,34.899999999999999,20,92,40,71,136,10],[45,3792,32.5,0,104,40,71,128,10],[46,2001,32.0,0,108,0,76,154,10],[47,5141,31.800000000000001,0,76,80,50,144,10],[48,1984,31.399999999999999,4,84,40,44,154,10],[49,1827,30.800000000000001,0,64,0,112,156,10],[50,2345,30.600000000000001,0,136,40,32,150,10],[51,1847,29.300000000000001,24,108,0,57,116,10],[52,1769,27.600000000000001,12,100,0,54,134,10],[53,1994,27.0,0,28,120,72,86,10],[54,2346,25.0,0,64,40,64,106,10]]
I want to get make an int for the rank. I checked it on JSONLint, and it is valid.
Here is my code:
Gson gson = new GsonBuilder().serializeNulls().create();
System.out.println("Connecting to The Blue Alliance");
String sURL = "http://www.thebluealliance.com/api/v2/event/2015mokc/rankings?X-TBA-App-Id=frc1810:alex-webber:v01";
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request
.getContent()));
JsonObject rootobj = root.getAsJsonObject();
String key = rootobj.get("key").toString();

That is because it is not an object type. From the Javadoc for JsonObject:
A class representing an object type in Json...
The type you are getting as a response is an array type, so you need to use JsonArray instead of JsonObject:
JsonArray jsonArray = root.getAsJsonArray();

Related

why should I need Explicit Type Conversion When Using JSONObject inside JsonArray?

I'm getting a JsonArray response from RestApi.
it looks like this.
[{"symbol":"BTC","volumeUsd24Hr":"9933608358.6769638763447470","marketCapUsd":"373762242595.8886412421003192","priceUsd":"19494.3435967958368457","vwap24Hr":"19703.2611157615056124","changePercent24Hr":"-2.4906058989768847","name":"Bitcoin","explorer":"https://blockchain.info/","rank":"1","id":"bitcoin","maxSupply":"21000000.0000000000000000","supply":"19172856.0000000000000000"},{"symbol":"ETH","volumeUsd24Hr":"3241023190.3730390178381998","marketCapUsd":"163079674691.9858451324912645","priceUsd":"1329.0704167150164988","vwap24Hr":"1337.1800236177182353","changePercent24Hr":"-2.1575264116384809","name":"Ethereum","explorer":"https://etherscan.io/","rank":"2","id":"ethereum","maxSupply":null,"supply":"122702057.4990000000000000"},{"symbol":"USDT","volumeUsd24Hr":"13840788061.6519189957942816","marketCapUsd":"68364449761.2046855857488307","priceUsd":"1.0004593774481033","vwap24Hr":"1.0004839031623615","changePercent24Hr":"0.0536998153626522","name":"Tether","explorer":"https://www.omniexplorer.info/asset/31","rank":"3","id":"tether","maxSupply":null,"supply":"68333059094.8965800000000000"},{"symbol"...
There are JsonArrays inside JsonObject.
And I wanna extract values from Each JsonObject(symbol).
So I checked the data type of JsonObject by printing jsonArray.get(0).getClass(), and it gives me "class org.json.simple.JSONObject" as expected.
so I tried to extract value by using
jsonArray.get(0).get("symbol");
but this code makes compile error saying " Cannot resolve method 'get' in 'Object' "
So I needed to explicitly convert data type into JSONObject like this
((JSONObject) jsonArray.get(0)).get("symbol")
then I got what I want.
What I'm wondering is that why should I explicitly convert jsonArray.get(0) to JSONObject,
even though .getclass() says that the type of data is JSONObject
Here are my Full Code .. Thanks in advance!!
public static void main(String[] args) throws IOException, ParseException {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("text/plain");
Request request = new Request.Builder()
.url("http://api.coincap.io/v2/assets")
.get()
.build();
Response response = client.newCall(request).execute();
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(response.body().string());
JSONArray jsonArray = (JSONArray) ((JSONObject) obj).get("data");
// JSONObject inside JSONArray
System.out.println(jsonArray.get(0).getClass());
System.out.println(((JSONObject) jsonArray.get(0)).get("symbol"));
}
Maybe you can try it
jsonArray.getJSONObject(0);

How to retreive data from Json using java

hi guys i have json response like this
Response response = service.execute(requestSendToNS);
// JSONObject jsonResponse = new JSONObject(response);
//String data = jsonResponse.getString("id");
System.out.println("Response Body : " + response.getBody());
and here the result :
Response Body : [{"status":"success","message":"update success","id":"1404","internalid":2604},{"status":"failed","message":"bad location is already used in another location","id":1405}]
my question is how to getting value "id" from my json response ?
i have try use this code :
// JSONObject jsonResponse = new JSONObject(response);
//String data = jsonResponse.getString("id");
i also have use this
List responseObject = objectMapper.readValue(response.getBody(),List);
but i cannot mapping from json Array to object
but i cannot retreive value from id
Your response body is an array.
[{...},{...}]
That's why you can't get id
String data = jsonResponse.getString("id");
Please have a look JsonReader to read json as JsonArray
https://docs.oracle.com/javaee/7/api/javax/json/JsonReader.html#readObject--
JsonReader jsonReader = Json.createReader(new StringReader(response.getBody()));
JsonArray array = jsonReader.readArray();
JsonObject obj = array.getJsonObject(0);
String data = obj.getString("id");
First, you have to create a class that has the exact same structure as the JSON response, and then you can use ObjectMapper from jackson library to write the JSON to class and read the values from it.

Java and simple json

I am trying to get from a json username this is the json
[{"user_id":"1","username":"THEUSERNAME","count300":"0","count100":"0","count50":"0","playcount":"0","ranked_score":"0","total_score":"0","pp_rank":"0","level":"0","pp_raw":"0","accuracy":"0","count_rank_ss":"0","count_rank_s":"0","count_rank_a":"0","country":"0","events":[]}]
My code is
URL url = new URL("url");
URLConnection c = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder b = new StringBuilder();
String line;
while ((line = in.readLine()) != null) b.append(line);
String text = b.toString();
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(text);
String username = (String) jsonObject.get("username");
System.out.println(username);
And the error i get
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at eu.dpp.ircbot.Ircbot.main(Ircbot.java:80)
Note the [] around your original string. This indicates that it's a JSONArray and not a JSONObject, which is exactly what the exception you get tells you. For the JSON specs, see http://json.org/
The actual object is surrounded with {}, you may be confused because you only have 1 object inside the array. But you still have to treat the string as an array and then iterate over the objects in it.

how to access json array element in java

i am getting json array in the output.i want to access the specific key elments from the response .how can i ..?
ResponseEntity <String> respone;
try {
response =
restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
String response=response.getBody();
JSONObject res = new JSONObject();
res.put("result", response);
System.out.println(res);
int len=res.size();
System.out.println(len);
JSONParser parser=new JSONParser();
Object obj = parser.parse(response);
JSONArray array = (JSONArray)obj;
System.out.println(array.get(0)); }
this is respponse format i m getting in output.i want to access the bid from the response.how can i?
[
{
"bName": "abc",
"bId": "n86nbnhbnghgy76"
}
]
Decode your string using JSONArray(String json) constructor:
String response = response.getBody();
JSONArray res = new JSONArray(response);
String bId = res.getJSONObject(0).get("bId");
System.out.println(bid);
EDIT
Try following:
String response=response.getBody();
JSONObject res = new JSONObject();
System.out.println(res);
int len=res.size();
System.out.println(len);
JSONParser parser=new JSONParser();
Object obj = parser.parse(response);
JSONArray array = (JSONArray)obj;
res=(JSONObject)array.get(0);
System.out.println(res.get("bId"));
Output :
n86nbnhbnghgy76
This one is based on your code and with Simple Json Library.

casting String to JSONObject

I have a json response from server, I get as string, and want to cast to JSONObject (import org.json.JSONObject;)
this is my casting:
JSONObject responseJson = new JSONObject(responseString);
and this is what I get:
responseString = {"code":0,"type":"success","description":null,"data":{"path":"http:........"}}
responseJson = {"class":"class java.lang.StringBuilder"}
does anyone knows why is responseJson not with correct values?
I can do
responseJson.getString("class")
but what I want to do is
responseJson.getString("type")
Try this way with json-simple
String jsonString = "{\"code\":0,\"type\":\"success\",\"description\":null,\"data\":
{\"path\":\"http:........\"}}";
org.json.simple.JSONObject json =(org.json.simple.JSONObject) new JSONParser()
.parse(jsonString);
System.out.println(json.get("data"));

Categories

Resources