How to retreive data from Json using java - 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.

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 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"));

JSONException - Parsing String to JSONArray

i want to parse some json downloaded from the web in a JSONArray.
Simple thing i think, but can't get it to work.
It seams that the JSON Format is the Problem. I tried different ways
to fix it, but nothing helps.
I download the String with this method:
private String DownloadContent(String URL) {
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch(Exception e) {
Log.e("log_tag", e.toString());
}
return result;
}
After that i try to parse the string to the JSONArray like this:
String resultString = DownloadContent(stringUrl);
JSONArray jArray = new JSONArray(resultString);
but everytime i get this exception:
i test the following to get the JSON right:
result = EntityUtils.toString(response.getEntity(), "UTF-8");
result = StringEscapeUtils.unescapeJson(EntityUtils.toString(response.getEntity()));
this methods changed the string but no time the JSON is valid (tested with this).
In my JSON are things like this:
Meine gr\\u00f6\\u00dfte Leidenschaft ist es
http:\\/\\/bla.de\\/wp-content\\/uploads\\/2014\\/02\\/hello.jpg
What should i do to get it right? I hope someone can help me :)
Thanks!
Looking at the detailMessage, it looks like you are trying to create a JSONArray from JSON that looks like
{"posts": [...]}
That's a JSON object, not an array. You'll need to parse it as a JSONObject and get the array object from it.
JSONObject object = new JSONObject(resultString);
JSONArray array = object.getJSONArray("posts"); // or whatever the method is to get a JSONArray element from the JSONObject
This is assuming you are trying to get the JSON array named posts.

How to put JSON information in an array to use it for displaying in ListView

I have an Activity which has three fragments and I am trying to retrieve a JSON file from my server which I will be updating on a daily basis.
My JSON file is located here: http://pagesbyz.com/test.json
Because there are fragments, I used the following code in my MainActivity class:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(), result, 2000).show();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
What I really need to do is retrieve the TYPE field in my JSON file and separate it into three tabs and put it inside a ListView like this:
I would like to know once I have read the JSON file by using the code on top how do I proceed... Thanks for the help :)
Should I query on each fragment and then look for the TYPE field? Would that be easier?
Curious as to why the Toast did not execute... Here is the pastebin for my main activity: http://pastebin.com/gKTCeH79
What you want to do is use Androids JSONObject and JSONArray to access your json data.
For example since your root is a json array you want to instantiate a JSONArray object from your json data you have.
JSONArray jsonArray = new JSONArray(jsonString);
Now from this array you can grab individual JSONObject for each object in your array.
JSONObject objectOne = new JSONObject(0); // Grabs your first item
From the JSONObject you can now access your three values.
String type = objectOne.get("type") // Will give you the value for type
JSONArray: http://developer.android.com/reference/org/json/JSONArray.html
JSONObject: http://developer.android.com/reference/org/json/JSONObject.html
Another way is to use a framework that lets you deserialize json into Java POJO's (Plain Old Java Objects). Gson is the easiest to use.
The basic idea is you make an object that relates directly to your json objects, after you have this you can easily store your data in java objects and use it however you like.
GSON example:
Gson gson = new Gson();
MyCustomClass obj2 = gson.fromJson(json, MyCustomClass.class);
Where MyCustomClass would contain the variables id, type, and data.
GSON reference: https://sites.google.com/site/gson/gson-user-guide
Good Luck!

Categories

Resources