how to access json array element in java - 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.
Related
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.
Assistance parsing with gson (google json)
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();
Get a value of json in android app
Get a value of json in android app my json result = {"message":"Json","success":1} Value {"message":"Json","success":1} of type org.json.JSONObject cannot be converted to JSONArray my code : HttpEntity ent= resp.getEntity(); text = EntityUtils.toString(ent); JSONArray json = new JSONArray(text); JSONObject jObj = json.getJSONObject(0); Integer sucess= jObj.getInt("success"); if (sucess == 1){ Log.v("JSON" ,"es 1"); }
Your are trying to convert a JSONObject to a JSONArray. Use this HttpEntity ent= resp.getEntity(); text = EntityUtils.toString(ent); JSONObject json = new JSONObject(text); int success= -1; if(json.has("success")) success = json.getInt("success"); if (success == 1){ Log.v("JSON" ,"es 1"); }
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"));
send json array as post parameter from android
I need to send json array as a paramater via post method from android ...and receive jsonarray as response.. what should be the conversion of below mentioned request in java..?? curl -H "X-OpenSRF-service: open-ils.search" --data 'osrf-msg=[{"__p" : {"threadTrace" : 0, "payload" : { "__c" : "osrfMethod","__p" : { "params" :"30007004981493","method" : "open-ils.search.biblio.find_by_barcode"}},"type" : "REQUEST","locale" : "en-US"},"__c" : "osrfMessage"} ]' http://localhost/osrf-http-translator i have done it like this.. HttpParams httpParams = new BasicHttpParams(); HttpClient client = new DefaultHttpClient(httpParams); HttpPost httpost = new HttpPost("http://"+hostname+"/osrf-http-translator"); // httpost.setHeader("Accept", "application/json"); // httpost.setHeader("Content-type", "application/json"); httpost.setHeader("X-OpenSRF-service", "open-ils.search"); System.out.println("2"); JSONObject data = new JSONObject(); JSONObject _p = new JSONObject(); JSONObject _p1 = new JSONObject(); JSONObject osrfmsg = new JSONObject(); HttpResponse response = null; try { _p.put("params",bookid);//"30007004981493" _p.put("method","open-ils.search.biblio.find_by_barcode"); JSONObject payload = new JSONObject(); payload.put("_c", "osrfMethod"); payload.put("_p", _p); _p1.put("threadTrace",0); _p1.put("payload", payload); _p1.put("locale","en-US" ); _p1.put("type", "REQUEST"); osrfmsg.put("_c","osrfMessage"); osrfmsg.put("_p",_p1); data.put("osrf-msg",osrfmsg); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONArray osrfmsg2=new JSONArray(); osrfmsg2.put(osrfmsg); httpost.getParams().setParameter("osrf-msg",osrfmsg2); response = client.execute(httpost); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(builder.toString()); JSONArray finalResult = new JSONArray(tokener); but i'm not able to get the json array... is there any other method?
Well you are constructing a JSONObject as the parameter, try using JSONArray as your payload object. JSONArray payload = new JSONArray(); And work with a collection. Hope that helps. Also your context type that you send is not JSON, it is form encoded