How to wrap given json to string and send it to server via Http put request in android?
This is how my json look like.
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
above is my json array.
below is how I wrote the code but, its not working
protected String doInBackground(Void... params) {
String text = null;
try {
JSONObject child1 = new JSONObject();
try{
child1.put("id", "LED");
child1.put("current_value", "0");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(child1);
JSONObject datastreams = new JSONObject();
datastreams.put("datastreams", jsonArray);
JSONObject version = new JSONObject();
version.put("version", "1.0.0");
version.put("version", datastreams);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPut put = new HttpPut("url");
put.addHeader("X-Apikey","");
StringEntity se = new StringEntity( version.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
put.addHeader("Accept", "application/json");
put.addHeader("Content-type", "application/json");
put.setEntity(se);
try{
HttpResponse response = httpClient.execute(put, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
}
catch (Exception e) {
return e.getLocalizedMessage();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return text;
}
please help on this
this is one sample.
JSONObject Parent = new JSONObject();
JSONArray array = new JSONArray();
for (int i = 0 ; i < datastreamList.size() ; i++)
{
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", datastreamList.get(i).GetId());
jsonObj.put("current_value", datastreamList.get(i).GetCurrentValue());
array.put(jsonObj);
}
Parent.put("datastreams", array);
Parent.put("version", version);
and for sending that:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity( Parent.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(se);
client.execute(post);
EDIT
in this sample datastreamList that used in for statement is a list that you must have for all value that want send to server ( one list of one class that have 2 property , id and value ), actually i think you have two class like bellow:
class A {
List<Datastreams> datastreamList
String version;
//get
//set
}
class Datastreams {
String id;
String current_value; // or int
//get
//set
}
and in your code you must have one object of A class that want send to server, so you can use first part to map your object to json.
If you prefer to use a library then I'll prefer you to use Ion Library by Kaush.
Form this library you can simply post your JSON like this :
JsonObject json = new JsonObject();
json.addProperty("foo", "bar");
Ion.with(context, "http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
}
});
Just you have to send as a String so store following JSON data in String
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
then you have to send like:
pairs.add(new BasicNameValuePair("data", finalJsonObject.toString()));
The '{' bracket represent a object and '[' represent an array or list. In your case create a bean
YourObj{
private String version;
private List<DataStream> datastreams;
//getters
//setters
}
DataStream{
private String id;
private String current_value;
//getters
//setters
}
use org.codehaus.jackson:jackson-xc jar for json parssing
use ObjectMapper
String to Object
YourObj obj = new ObjectMapper().readValue(stringyouwanttopass,new TypeReference<YourObj>(){});
now you can use the parsed value.
or you can set the values to the YourObj
YourObj obj =new YourObj();
obj.setVersion(1.0.0);
List<Datastream> datastreams=new ArrayList<Datastream>();
Datastream datestr=new Datastream();
datestr.setId("example");
datestr.setCurrent_value("333");
datastreams.add(datestr);
datestr.setId("key");
datestr.setCurrent_value("value");
datastreams.add(datestr);
datestr.setId("datastream");
datestr.setCurrent_value("1337");
datastreams.add(datestr);
JSONObject jsonget = new JSONObject(appObject);
jsonget.toString();
Connecting server using Jersey
Client client = Client.create();
WebResource webResource = client.resource("serverURl");
ClientResponse response = webResource.path("somePath")
.type("application/json").accept("application/json")
.post(ClientResponse.class, jsonget.toString());
in the server side get it as string and parse it.
here is a android Client library can help you:
Httpzoid - Android REST (JSON) Client,it has some examples and you can do put post,get request easily.
https://github.com/kodart/Httpzoid
Related
I want to fetch data from the Web service HttpGet Method. Web Service needs two header information.
How can i add set Parameters ?
"Content-Type", "application/json"
"Authorization", "Bearer " + Utils.PreferencesGetir(ActivityPuanlarim.this, "Preferences_Token"))
Json Data
[
{
"ID": 12,
"KayitTarihi": "2016-07-21T08:37:01.603",
"KullanilanPuan": 0,
"KuponID": 2,
"KuponKullanim": [],
"KuponNo": "S7240061",
"KuponAciklama": "Açıklama 1",
"Puan": 40
},
{
"ID": 13,
"KayitTarihi": "2016-07-21T09:38:48.877",
"KullanilanPuan": 0,
"KuponID": 2,
"KuponKullanim": [],
"KuponNo": "S7240071",
"KuponAciklama": "Açıklama 2",
"Puan": 40
}
]
AsyncTask doInBackground
#Override
protected Void doInBackground(Void... voids) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Content-Type", "application/json"));
params.add(new BasicNameValuePair("Authorization", "Bearer " + Utils.PreferencesGetir(ActivityPuanlarim.this, "Preferences_Token")));
JSONArray json = jParser.makeHttpRequestArray(URL, "GET", params);
try {
if (Utils.InternetKontrol(ActivityPuanlarim.this) == true) {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
String id = c.getString("ID");
String kayitTarihi = c.getString("KayitTarihi");
String kullanilanPuan = c.getString("KullanilanPuan");
String kuponID = c.getString("KuponID");
String kuponKullanim = c.getString("KuponKullanim");
String kuponNo = c.getString("KuponNo");
String kuponAciklama = c.getString("KuponAciklama");
String puan = c.getString("Puan");
// Hashmap oluşturulur
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", id);
map.put("KayitTarihi", kayitTarihi);
map.put("KullanilanPuan", kullanilanPuan);
map.put("KuponID", kuponID);
map.put("KuponKullanim", kuponKullanim);
map.put("KuponNo", kuponNo);
map.put("KuponAciklama", kuponAciklama);
map.put("Puan", puan);
puanlarimTumKayitlarList.add(map);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
As you do not send a HttpRequest, you don't need these parameters. You should rather request content from Servlet via URLConnection and then read the data in your activity.
Example here:
https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
Edit:
I've read that you can use HttpGet in Activity like this:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("key", VALUE);
HttpResponse httpResponse = httpClient.execute(httpGet);
I have made a call to the Instagram Endpoint for images that contain the tag #selfie. The issue I am having is in dealing with the response. I get a massive JSON Response, and all I really need is the "thumbnail" image "url".
How can I go about structuring an Object from the Data that is in the JSONObject?
public static class FetchTaggedImages extends AsyncTask<String, Void, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
String mAccessToken = params[0];
String url = (API_URL + "?access_token=" + mAccessToken);
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
String instagramJSONResponse = null;
JSONArray responseArray = null;
HttpResponse postResponse;
try {
postResponse = httpclient.execute(httpGet);
instagramJSONResponse = EntityUtils.toString(postResponse
.getEntity());
JSONObject jsonObject = new JSONObject(instagramJSONResponse);
String thumbnail = jsonObject.getString("url");
responseArray = new JSONArray(instagramJSONResponse);
Log.e("RESPONSE", instagramJSONResponse);
} catch (Exception ex) {
ex.printStackTrace();
}
return responseArray;
}
#Override
protected void onPostExecute(JSONArray response) {
// TODO Auto-generated method stub
super.onPostExecute(response);
Log.e("ONPOSTEXECUTE", "ONPOSTEXECUTE");
JSONObject jsonObject;
}
}
HERE IS A SAMPLE OF THE JSON STRING
{
"data":[
{
"tags":[
"summer",
"love",
"tagstagram",
"colorful",
"instalike",
"selfie",
"swag",
"instago",
"igers",
"follow4follow",
"follow",
"instadaily",
"friends",
"style",
"webstagram",
"look",
"instafollow",
"iphoneonly",
"instagood",
"amazing",
"instacool",
"bestoftheday",
"fun",
"followme",
"like4like",
"picoftheday",
"photooftheday"
],
"location":null,
"link":"http:\/\/instagram.com\/p\/wFlirqPxAW\/",
"user_has_liked":false,
"caption":{
"id":"866263615190011927",
"created_time":"1417486691",
"text":"First contest of the season 🏄",
"from":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"full_name":"Juan Basave"
}
},
"type":"image",
"id":"866263614401482774_507279035",
"likes":{
"data":[
{
"id":"956576929",
"profile_picture":"https:\/\/igcdn-photos-e-a.akamaihd.net\/hphotos-ak-xfa1\/10802992_1561400387426348_1634151041_a.jpg",
"username":"don_assi2014",
"full_name":"-Ali Assi-"
},
{
"id":"520771011",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfa1\/1889350_1565133803717465_1353157813_a.jpg",
"username":"michelle.y6",
"full_name":"Michelle Y"
},
{
"id":"873300277",
"profile_picture":"https:\/\/igcdn-photos-g-a.akamaihd.net\/hphotos-ak-xfa1\/10817804_1543101285933854_123980756_a.jpg",
"username":"ayah_shahbanderr",
"full_name":"Ayah"
},
{
"id":"199966711",
"profile_picture":"https:\/\/igcdn-photos-a-a.akamaihd.net\/hphotos-ak-xfa1\/10617174_587781691338392_1164910966_a.jpg",
"username":"elijah_reissman_",
"full_name":"Elijah Reissman"
}
],
"count":13
},
"images":{
"low_resolution":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_a.jpg",
"height":306,
"width":306
},
"standard_resolution":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_n.jpg",
"height":640,
"width":640
},
"thumbnail":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_s.jpg",
"height":150,
"width":150
}
},
"users_in_photo":[
],
"created_time":"1417486691",
"user":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"bio":"",
"website":"",
"full_name":"Juan Basave"
},
"filter":"Mayfair",
"comments":{
"data":[
{
"id":"866282245801841449",
"created_time":"1417488912",
"text":"#TagStaGram #love #friends #tagstagram #photooftheday #selfie #amazing #followme #follow4follow #like4like #look #instalike #igers #picoftheday #instadaily #instafollow #fun #iphoneonly #instagood #bestoftheday #instacool #instago #summer #follow #webstagram #colorful #style #swag",
"from":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"full_name":"Juan Basave"
}
}
],
"count":1
},
"attribution":null
},
"thumbnail" is in "images" object, and "images" object is in a first object of the "data" array.
So you need to obtain the "data" JSONArray first, access for each array item, find "images" object from the item, and finally you can access "thumbnail" object.
Your code seems to access to "url" in the top level object that does not have "url" property.
If you'd like to access via JSONObject framework, you should implement the code like this:
public String getUrl(JSONObject response) throws JSONException {
JSONArray data = response.getJSONArray("data");
JSONObject object = data.getJSONObject(0);
JSONObject images = object.getJSONObject("images");
JSONObject thumbnail = images.getJSONObject("thumbnail");
return thumbnail.getString("url");
}
If you need a collection of the url, you need to iterate accessing all data objects like this:
JSONArray data = response.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(0);
// ...
}
This is a basic function for dealing with JSON string that Android Framework provides.
If you feel that it is a long way to go, consider using GSON or Jackson JSON Processor.
I cannot post or send my JSON string t ASP.NET C# based web server from android.
Here is my code, I have retrieve data from SQLite database using cursor and which I have converted these data into JSONobject and then JSONstring.
Code are given below:
protected Boolean doInBackground(final String... args) {
try {
JSONObject parrent = new JSONObject();
// JSONObject jMainObject = new JSONObject();
JSONArray jArray = new JSONArray();
Cursor Online = MainActivity.mydb.rawQuery("select * from myTable", null);
while (Online.moveToNext()) {
JSONObject jObject = new JSONObject();
jObject.put("CategoryType", Online.getString(0));
jObject.put("CategoryID", Online.getString(1));
jObject.put("CategoryName", Online.getString(2));
jObject.put("CustomerId", Online.getString(3));
jObject.put("CustomerName", Online.getString(4));
jObject.put("Accountno", Online.getString(5));
jObject.put("Balance", Online.getString(6));
jObject.put("Installment", Online.getString(7));
jObject.put("Amount", Online.getString(8));
jObject.put("Collected", Online.getString(9));
jObject.put("Dueinstnum", Online.getString(10));
jObject.put("customer_id", Online.getString(11));
jObject.put("dueInstNum", Online.getString(12));
jObject.put("account_id", Online.getString(13));
jObject.put("branch_id", Online.getString(14));
jObject.put("customer_id", Online.getString(15));
jObject.put("id", Online.getString(16));
jArray.put(jObject);
// String JSONString = jObject.toString();
}
parrent.put("FildCollections", jArray);
parrent.put("ProgramOrganizerId","70cff4d5-cc0f-4bf8-80de-23dd82d90719");
parrent.put("BranchId", "bde14105-4617-4d07-9ab8-a95e98f8c5a5");
parrent.put("Password", "Pass#123");
parrent.put("UserId", "5103");
But now after that very next line I want to send this JSONstring to C# web Server
Code:
HttpPost httppost = new HttpPost("Posting url");
StringEntity entity = new StringEntity(parrent.toString(),
"UTF-8");
entity.setContentType("application/json;charset=UTF-8");// text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
httppost.addHeader("language", "en");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("user_Id", "5103");
httppost.addHeader("user_Pass", "Pass#123");
httppost.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httppost);
return true;
}
I have call my function from sub menu like this:
calling Function code:
case R.id.submenu1_1:
if (item.isChecked())
item.setChecked(false);
else {
item.setChecked(true);
// Export Online
try {
new ExportDatabaseOnline().execute();
} catch (Exception ex) {
Log.e("Error in ActivityB", ex.toString());
}
}
// Toast.makeText(this, "Clicked: Menu No. 2 - SubMenu No .1",
// Toast.LENGTH_SHORT).show();
return true;
Now the full function code which I have told you earlier in partial. So my full function code is:
public class ExportDatabaseOnline extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
// private HttpResponse response;
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait...");
this.dialog.setTitle("Exporting Database To Online");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
JSONObject parrent = new JSONObject();
// JSONObject jMainObject = new JSONObject();
JSONArray jArray = new JSONArray();
Cursor Online = MainActivity.mydb.rawQuery("select * from myTable", null);
while (Online.moveToNext()) {
JSONObject jObject = new JSONObject();
jObject.put("CategoryType", Online.getString(0));
jObject.put("CategoryID", Online.getString(1));
jObject.put("CategoryName", Online.getString(2));
jObject.put("CustomerId", Online.getString(3));
jObject.put("CustomerName", Online.getString(4));
jObject.put("Accountno", Online.getString(5));
jObject.put("Balance", Online.getString(6));
jObject.put("Installment", Online.getString(7));
jObject.put("Amount", Online.getString(8));
jObject.put("Collected", Online.getString(9));
jObject.put("Dueinstnum", Online.getString(10));
jObject.put("customer_id", Online.getString(11));
jObject.put("dueInstNum", Online.getString(12));
jObject.put("account_id", Online.getString(13));
jObject.put("branch_id", Online.getString(14));
jObject.put("customer_id", Online.getString(15));
jObject.put("id", Online.getString(16));
jArray.put(jObject);
// String JSONString = jObject.toString();
}
parrent.put("FildCollections", jArray);
parrent.put("ProgramOrganizerId","70cff4d5-cc0f-4bf8-80de-23dd82d90719");
parrent.put("BranchId", "bde14105-4617-4d07-9ab8-a95e98f8c5a5");
parrent.put("Password", "Pass#123");
parrent.put("UserId", "5103");
HttpPost httppost = new HttpPost("Posting url");
StringEntity entity = new StringEntity(parrent.toString(),"UTF-8");
entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httppost.addHeader("language", "en");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("user_Id", "5103");
httppost.addHeader("user_Pass", "Pass#123");
httppost.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httppost);
return true;
} catch (Exception e) {
Log.e("ActivityB", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (success) {
Toast.makeText(MainActivity.this, "Export successful!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Export failed",
Toast.LENGTH_SHORT).show();
}
}
}
This code is not working, it shows successful message but doesn't post any JSON string to the website.
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 have to pass a json object with a method and multiple parameters
the object must have this form
{"method":"startSession","params":"["email" "testmail#test.it", "password" "1234", "stayLogged" "1", "idClient" "IPHONE"]"}
My code in android to send this object is
HttpPost httppost = new HttpPost(BASE_URI);
JSONObject json = new JSONObject();
String email="testmail#test.it";
String emailRic="email"+" "+"\""+email+"\"";
String password="1234";
String passwordRic="password"+" "+"\""+password+"\"";
String stayLogged="1";
String stayLoggedRic="stayLogged"+" "+"\""+stayLogged+"\"";
String idClient="ANDROID";
String idClientRic="idClient"+" "+"\""+idClient+"\"";
try {
List<String> accessParameters=new ArrayList<String>();
accessParameters.add(emailRic);
accessParameters.add(passwordRic);
accessParameters.add(stayLoggedRic);
accessParameters.add(idClientRic);
String par=accessParameters.toString();
json.put("method", "startSession");
json.put("params", par);
JSONArray postjson=new JSONArray();
postjson.put(json);
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
System.out.print(json);
HttpResponse response = mClient.execute(httppost);
if(response != null){
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
System.out.println("the answer is:\n"+sb);
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// text = sb.toString();
}
// tv.setText(text);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
But this send an object with the wrong form
{"method":"startSession","params":"[\"email\" \"testmail#test.it\", \"password\" \"1234\", \"restaConnesso\" \"1\", \"idClient\" \"IPHONE\"]"}
(I have seen this in the debugger)
if I try to remove the value \" from the piece of code
String email="testmail#test.it";
String emailRic="email"+" "+"\""+email+"\"";
String password="1234";
String passwordRic="password"+" "+"\""+password+"\"";
String stayLogged="1";
String stayLoggedRic="stayLogged"+" "+"\""+stayLogged+"\"";
String idClient="ANDROID";
String idClientRic="idClient"+" "+"\""+idClient+"\"";
The object sent assume the form
{"method":"startSession","params":"[email testmail#test.it, password 1234, restaConnesso 1, idClient IPHONE]"}
how can I sent the json with exacty this sintax???
{"method":"startSession","params":"["email" "testmail#test.it", "password" "1234", "stayLogged" "1", "idClient" "IPHONE"]"}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
//Firstly declare & create a json object from the desired json as a whole.
/* How to create Json*/
JSONObject jObjectData = new JSONObject();
// Create Json Object using Facebook Data
jObjectData.put("method", "startSession");
ArrayList<String> list = new ArrayList<String>();
list.add("email");
list.add("testmail#test.it");
etc... ....
JSONArray jsArray = new JSONArray(list);
jObjectData.put("params", jsArray);
StringEntity stringEntity = new StringEntity(jObjectData.toString());
httpost.setEntity(stringEntity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
response = httpclient.execute(httpost, responseHandler);
/* Create Json object for set parameter*/
JSONObject jObjectData = new JSONObject();
// set your first parameter name
jObjectData.put("parameter1", "startSession");
ArrayList<JSONObject> list = new ArrayList<JSONObject>();
// for 1 parameter
JSONObject jObjectData1 = new JSONObject();
jObjectData1.put("email","testmail#test.it");
jObjectData1.put("password","1234");
jObjectData1.put("stayLogged","1");
jObjectData1.put("idClient","IPHONE");
list.add(jObjectData1);
JSONArray jsArray = new JSONArray(list);
// set your second parameter has more value
jObjectData.put("parameter2", jsArray);
jObjectData string is look like below string:-
{"parameter1":"startSession",
"parameter2": [{ "email": "testmail#test.it",
"password": "1234",
"stayLogged": "1",
"idClient": "IPHONE"
}]
}
I'm not sure but, isn't the problem the fact that you are trying to send an array but are instead sending a string?
Original:
{"method":"startSession",
"params":"["email" "testmail#test.it", "password" "1234", "stayLogged" "1", "idClient" "IPHONE"]"}
Should be something like this instead (no quotes around the array):
{"method":"startSession",
"params": ["email" "testmail#test.it", "password" "1234", "stayLogged" "1", "idClient" "IPHONE"]}
Edit: Actually I think you actually want a nested object:
{"method":"startSession",
"params": { "email": "testmail#test.it",
"password": "1234",
"stayLogged": "1",
"idClient": "IPHONE"
}
}
No?
Edit #2: You should take a look at how to properly use JSONArray and JSONObject, this page has some good examples.