Get a value of json in android app - java

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

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.

How can i convert JSON data present in a URL into a JSON string in java or android?

I tried the code in android below:-
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://echo.jsontest.com/key/value/one/two");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
JSONArray jsonObj = new JSONArray(entity);
System.out.print("message is"+jsonObj);
}
catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
//Below i am displaying in my layout in my emulator
protected void onPostExecute(String results) {
if (results!=null) {
TextView et = (TextView)findViewById(R.id.data);
et.setText(results);
}
Button b = (Button)findViewById(R.id.getvehicles);
b.setClickable(true);
}
so when i just use getASCIIContentFromEntity(entity) ,then i am able to print full JSON data as it is.but instead i wanna print only the values inside this URL it is JSON data,please open to see it .
How can i fetch the values inside this json URL?
Your response is in a JSONObject form so you have to get it like this.
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
Object content = EntityUtils.toString(entity);
JSONObject jsonObj = new JSONObject(content.toString());
System.out.print("message is"+jsonObj.toString());
Then your JSONObject contains multiple values, you can get it by using the "key" of the pair.
String value = jsonObj.getString(key); //String value = jsonObj.getString("one");
In your case you want to print one and two, which means the kay and value, so you have to iterate the entire collection like this(If you know the keys used in the response no need of using this method).
Iterator<?> keys = jsonObj.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
System.out.print("key - value"+ key + jsonObj.getString(key));
}

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 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.

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

Categories

Resources