I want to get the value of "result" from the below JSON response and store it locally.Here's the code:
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
//JSONArray contacts;
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
My Response :
{"response":
[{
"name":"ajay",
"class":"7",
},
{
"rank":1
}],
"date":
{
"startdate":2/12/2012,
},
"result":"pass"
}
You need to create a JSON Object from json String, you get and then retrieve its data:
JSONObject json= new JSONObject(responseString); //your response
try {
String result = json.getString("result"); //result is key for which you need to retrieve data
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope it helps.
Please provide correct and full JSON response. So I can show you the way to parse the JSON :
String jsonStr; // hold your JSON response in String
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// If you have array
JSONArray resultArray = jsonObj.getJSONArray("response"); // Here you will get the Array
// Iterate the loop
for (int i = 0; i < resultArray.length(); i++) {
// get value with the NODE key
JSONObject obj = resultArray.getJSONObject(i);
String name = obj.getString("name");
}
// If you have object
String result = json.getString("result");
} catch (Exception e) {
e.printStackTrace();
}
Try like this...
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject json= new JSONObject(jsonStr); //your json response
String result = json.getString("result"); //result data
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Related
When I'm JSONObject jsonObj = new JSONObject(jsonStr);
I enter in catch because my json is not a array.
How can I get this format ?
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:8080/PFA/crimes";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String day_week = c.getString("day_week");
String naturecode = c.getString("naturecode");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("day_week", day_week);
contact.put("naturecode", naturecode);
// adding contact to contact list
List.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
JSON:
{
"crime": {
"compnos": "zerezrerzerezzr",
"day_week": "rtkeertoeirtj ,ertkierj",
"domestic": "false",
"fromdate": "ekrjtner",
"id": "1",
"location": "etritkjrtoijty",
"main_crimecode": "oijereriotjeroi",
"month": "455",
"naturecode": "zetzeeztet",
"reportingarea": "58",
"reptdistrict": "zorigjrgoijtoi",
"shift": "rektenrloj",
"shooting": "true",
"streetname": "kjrtnerkj",
"ucrpart": "irtjeroitejroirj",
"weapontype": "kejfnergkrtnh",
"x": "11",
"xstreetname": "zekjrnetk",
"y": "11",
"year": "45"
}
}
JsonObject crime = jsonObj.getJsonObject("crime");
JsonObject compnos = crime.getJsonObject("compnos");
.
..
...
There is no jsonArray in your json value. Give up to get jsonArray.
Try this:
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonMetaObject = jsonMasterObject.getJSONObject("crime");
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
Because you get jsonObject in key of crime not JsonArray.
I can retrieve data through JSON in listview but I want to show data relative to the user logged in so for that I have to Post username to PHP script. I don't have any idea how to post the username to PHP script and then get respond from web server.
private class GetFixture extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg) {
ServiceHandler serviceClient = new ServiceHandler();
Log.d("url: ", "> " + URL_ITEMS);
String json = serviceClient.makeServiceCall(URL_ITEMS,ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture resps","> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_MATCHID);
Log.d("matchId", matchId);
String teamA = c.getString(TAG_TEAMA);
Log.d("teamA", teamA);
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_MATCHID, matchId);
matchFixture.put(TAG_TEAMA, teamA);
matchFixture.put(TAG_TEAMB, teamB);
matchFixtureList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d("catch", "in the catch");
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
Doctor_Names.this, matchFixtureList,
R.layout.list_item, new String[] {
TAG_MATCHID, TAG_TEAMA,TAG_TEAMB
}
, new int[] {
R.id.teamA,R.id.name,
R.id.teamB
}
);
setListAdapter(adapter);
}
sir this code perfectly show me all data from this server but i want some specific data like i want to show data related to the person who is logged in so for that i have to pass the user name to PHP script so dont have idea to POST any thing to web on the basis of which i can filter data
Here is an example:
JSONObject obj = new JSONObject();
obj.put("username", "YourUser");
HttpUrlConnectionJson.sendHTTPData("http://" + serverAddress + "/api/SomeUserMethod", obj);
HttpUrlConnectionJson class
public class HttpUrlConnectionJson {
private static final String TAG = "HttpUrlConnectionJson";
public static String sendHTTPData(String urlpath, JSONObject json) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json.toString());
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d(TAG, stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e(TAG, connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e(TAG, exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
I hope this help
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 8 years ago.
Facing JSONException while parsing JSON String
Exception :
org.json.JSONException: Value anyType of type java.lang.String cannot be converted to JSONArray
Code snippet.
try {
androidHttpTransport.call(Soap_Action1, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
String resp=response.toString();
Log.d("resp",response.toString());
// newwwwww
try {
JSONArray jsonArray = new JSONArray(resp);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
System.out.println(c.getInt("MST_BloodGroupID"));
System.out.println(c.getString("BloodGroup_Name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
response.toString() is below:
anyType{schema=anyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{};
element=anyType{}; }; }; }; }; }; }; };
diffgram=anyType{DocumentElement=anyType{Table=anyType{MST_BloodGroupID=1;
BloodGroup_Name=A+; }; Table=anyType{MST_BloodGroupID=2;
BloodGroup_Name=A-; }; Table=anyType{MST_BloodGroupID=3;
BloodGroup_Name=B+; }; Table=anyType{MST_BloodGroupID=4;
BloodGroup_Name=B-; }; Table=anyType{MST_BloodGroupID=5;
BloodGroup_Name=AB+; }; Table=anyType{MST_BloodGroupID=6;
BloodGroup_Name=AB-; }; Table=anyType{MST_BloodGroupID=7;
BloodGroup_Name=O+; }; Table=anyType{MST_BloodGroupID=8;
BloodGroup_Name=O-; }; }; }; }
private class GetCategories extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Fetching..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
System.out.println(catObj.getInt("id"));
System.out.println(catObj.getString("name"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
Your response.toString() is not returning data that is valid JSON. A quick way to check if your strings are ever valid JSON is to plug it into this site: http://jsonviewer.stack.hu/
If it's valid, you can switch over to the viewer tab and visualize your json to make sure your code is checking for JSONArrays and JSONObjects in relation to the brackets and curly braces correctly, most errors I've experienced with parsing JSON stem from me just misreading my dataset. The site will shout loudly at you if it's invalid, as it does with your data.
I'd recommend using the GSON library to create your JSON data. After importing it into your project, you can use it like:
Gson gson = new Gson();
SoapObject response = (SoapObject) envelope.getResponse();
String resp = gson.toJson(response);
Beyond that your approach to creating JSON objects and arrays from the string data seems to be correct.
You can't convert the String to JSONArray becayse the Strings isn't Array its an JSONObject.
try to convert the String to JSONObject the get the array from the JSONObject using it's key.
I am parsing a json ,which is a json object to start with.it has an array html_attributions[] and another array results[]
Now as i create the json string from the URL, I can see my json string is coming. But in creating the json object from the json string I am having illegalArugumentException , illegal character in scheme at index 0.
My objective is to find the locations from the json and mark that in my google mapview.
here is my asynctask class..
class LocationJSON extends AsyncTask<String, Integer, Long> {
#Override
protected Long doInBackground(String... arg0) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();String url = jParser.getJSONStringFromUrl("https://maps.googleapis.com/maps/api/place/search/json?location=37.78583400,-122.40641700&radius=1500&types=gas_station&sensor=true&key=AIzaSyBIwW4m6xINOhM_j7hckMAbD3oks_fkLFc");
//main json abject
jsonObject = jParser.getJSONObject(url);
//get to the results array:
try {
JSONArray htmlArray = jsonObject.getJSONArray("html_attributions");
JSONArray resultsArray = jsonObject.getJSONArray("results");
//get to the geometry objects
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject geometry = resultsArray.getJSONObject(i);
//get to the location object
JSONObject location = geometry.getJSONObject("location");
//get to the lat string
double lati = Double.parseDouble(location.getString("Lat"));
double longi = Double.parseDouble(location.getString("lng"));
//create a latlong object
place = new LatLng(lati,longi);
/*//set the map
Marker melbourne = map.addMarker(new MarkerOptions()
.position(place)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//set the camera
cameraUpdate = CameraUpdateFactory.newLatLngZoom(place, 10);
map.animateCamera(cameraUpdate);*/
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//set the map
Marker melbourne = map.addMarker(new MarkerOptions()
.position(place)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//set the camera
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place, 10);
map.animateCamera(cameraUpdate);
}
}
//here is my jsonparser class public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static JSONArray jArray = null;
// constructor
public JSONParser() {
}
public String getJSONStringFromUrl(String url) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return json;
}
public JSONObject getJSONObject(String url) {
// try parse the string to a JSON object
getJSONStringFromUrl(url);
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser Object",
"Error parsing jsonObject " + e.toString());
}
// return JSON String
return jObj;
}
public JSONArray getJSONArray(String url) {
// try parse the string to a JSON array
getJSONStringFromUrl(url);
try {
jArray = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser Array",
"Error parsing jsonArray " + e.toString());
}
// return JSON String
return jArray;
}
}
here is the json data
{
"html_attributions": [
],
"results": [
{
"geometry": {
"location": {
"lat": 37.7774450,
"lng": -122.4048230
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/gas_station-71.png",
"id": "8e31a915604dd3597225152bfd3ec6f9bfa39395",
"name": "Chevron",
"photos": [
{
"height": 640,
"html_attributions": [
"From a Google User"
],
"photo_reference": "CnRiAAAADAcSOQpR_AW86egDLCWLpuEf00zuXUVFbcxh5-zCY5OzIUtJx764rn2mLnWTMA0xsz3AG7e0ZbU3n_GTJcOI0O15N1Va34GhUMiXirAw6h0DUETlElRwzvNjv1sQoFdimUYCOg-Us4ow9hoeq4cx-RIQSqRYof89YFdoVKRokkHN6RoUT4nJ4eofBuD1pJgwVeIKiaOlVo4",
"width": 480
}
],
"rating": 3.20,
"reference": "CnRkAAAAQ8TbCf9PqmO-_2-vgbFdrKE9j5PIknybR43IdTMziGYAuj5yOW3PcCCfLMgaeEM0ulLWU2WI3-YX14d1bza8tDYAEQlsP4JMTRT1RAeCm_CzhhhcZaB6UZ2Q2_f33iNHxMvoPumNwef6OXXmPQkusxIQ80SUv_R8odDO1dds5ovKZBoURT26TM5W2qKebWGQxfPE0SRgLwQ",
"types": [
"car_repair",
"gas_station",
"establishment"
],
"vicinity": "1000 Harrison Street, San Francisco"
},
],
"status": "OK"
}
-Mahaveer Muttha is right.
Here checkout the Gson Guide
Gson User Guide with tutorial
How I'm parsing google places response to get names of locations:
//data is a String with your JSON
JSONObject jsonObject = new JSONObject(data);
JSONArray googlePlaces = jsonObject.getJSONArray("results");
String[] googlePlacesNames = getStringFromJsonArray(googlePlaces, "name");
private String[] getStringFromJsonArray(JSONArray source, String fieldName){
String result[] = new String[source.length()];
JSONObject json;
try {
for (int i=0; i<source.length();i++) {
json = source.getJSONObject(i);
result[i]=json.getString("name");
Log.d("Places", "Next museum: " + result[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Advice to use GSON for parsing JSON objects is worth attention. By the way, Jackson library could be even better solution for json parsing: http://jackson.codehaus.org/
This way of passing JSON String to Object is more prone to errors. My advice is to use the Spring RestTemplate There you will not have to manipulate the JSON Objects manually. The RestTemplate will get everything done for you when it comes to serializing and desalinizing the JSON String. You will only need to have an entity class which you will have all the fields related to the Gas Stations. You can request a List of Gas Stations even from the RestTemplate. It's a matter of dealing with Java Objects and not this burden of JSON String manipulating manually.
RestTemplate restTemplate = new RestTemplate();
List<GasStation> stations = (List) restTemplate.getForObject(yourURL, List.class);
The above code will get you a list of Gas Stations to your code.
i m getting this response in a result of GET request to server
{"LL": { "control": "dev/sys/getkey", "value": "4545453030304138303046392035343733373432363020323031332D30322D31312031383A30313A3135", "Code": "200"}}
i just want to extract the value of "value" from the above json response.
I m using this code to get this response
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.14.247/jdev/sys/getkey"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("Parse Exception", e + "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("IO Exception 2", e + "");
}
Log.i("responseText", responseText);
Toast.makeText(MainActivity.this, responseText + "",
Toast.LENGTH_SHORT).show();
}
});
my question is that how can i parse this and get the value of only "value" tag.
thanks
you can parse current json String to get value from it as :
// Convert String to json object
JSONObject json = new JSONObject(responseText);
// get LL json object
JSONObject json_LL = json.getJSONObject("LL");
// get value from LL Json Object
String str_value=json_LL.getString("value"); //<< get value here
try this
JSONObject json = (JSONObject) JSONSerializer.toJSON(responseText);
String value = json.getJSONObject("LL").getString("value");
Try this:
JSONObject json= json1.getJSONObject("LL");
String value= json.getString("value");
Try this,
JSONObject ResponseObject = new JSONObject(Response);
String str = ResponseObject.getJSONObject("LL").getString(value);
You can parse your response and get value try this:
try {
JSONObject jsonObject = new JSONObject(response);// Convert response string in to json object.
JSONObject jsonLL = jsonObject.getJSONObject("LL");// Get LL json object from jsonObject.
String strValue = jsonLL.getString("value");// Get value from jsonLL Object.
} catch (Exception e) {
e.printStackTrace();
}
Simple and Efficient solution : Use Googlle's Gson library
Put this in build.gradle file : implementation 'com.google.code.gson:gson:2.6.2'
Now convert the JSON String to a convenient datastrucutre like HashMap in 2 lines like this.
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(JsonString , type);
or you can use this below class :
To convert your JSON string to hashmap use this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
Thank me later :)