JSONException - Parsing String to JSONArray - java

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.

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.

passing json reply from webservice to variables

i'm posting some data to a web service and i'm getting a json reply which i want to pass to a jsonobject.
The reply of the web service is:
{
"ValidateLoginResult": [
{
"ErrorMessage": "Wrong username pass",
"PropertyName": null
}
]
}
and i want to pass the error message and the property name to variables. I tried using JSONobject and JSONarray but didnt have any luck
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(serverURL);
StringEntity se = new StringEntity(data);
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. Getting Reply
inputStream = httpResponse.getEntity().getContent();
...
...
JSONArray json = new JSONArray(convertInputStreamToString(inputStream));
JSONObject json_LL = json.getJSONObject(0);
String str_value=json_LL.getString("ErrorMessage");
You are getting response in JSONObject and you are trying to get it in JSONArray.. thats why you are getting error..
Try this way...
try {
JSONObject result = new JSONObject(response);
if(data.has("ValidateLoginResult"){
JSONArray array = result.getJSONArray("ValidateLoginResult");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String ErrorMessage= ""+obj.getString("ErrorMessage");
String PropertyName= ""+obj.getString("PropertyName");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
OR
if you want one line answer..Try this..
// going directly to array object..
JSONObject result = new JSONObject(response).getJSONArray("ValidateLoginResult").getJSONObject(0);
String ErrorMessage= ""+result.getString("ErrorMessage");
String PropertyName= ""+result.getString("PropertyName");

How to get part of httpResponse in java

I want to get just ID from httpResponse after I did HttpGet.
This is my code:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:80/api/");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
which returns this:
{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"nameGroup":false,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-01T08:31:01.139Z"}],"name":"John"}]}
But I just want Oid not the whole thing. Any idea?
Thanks
Strint you've got is json encoded data, so you need to decode it and than you are able to access the field "oid". There are several libaries around to acomplish this job:
gson
JsonSimple
Jackson etc.
My favorite for small projects is gson
Using Jackson or Gson, you can parse the response JSON and get exactly the part you need.
If you don't need the whole result, then there is no point in creating a reference object, just manually traverse the json document, e.g.
mapper.readTree(responseText).get("foo").get("bar")
I think instead of using a library just to get value of one parameter is not appropriate if you have other options available. I would suggest you to parse the json on yor own using the APIs provided. You can try following:
try {
JSONObject obj = new JSONObject(your_json_string);
String value= null;
if (obj != null && obj.has(YOUR_KEY_FOR_PARAM)) {
value = obj.getString(YOUR_KEY_FOR_PARAM));
}
}

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