I need to access a .Net web service in Rest format using JSON. I m
pretty new to this concept and very much confused about how this
works....
Any one who can give an overview of this. I need the steps that I
need to follow to use JSON. Right now my doubt is how to use JSON to
grab to output.
This is the simplest way to parse Json web servie
String str="url";
try{
URL url=new URL(str);
URLConnection urlc=url.openConnection();
BufferedReader bfr=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String line;
while((line=bfr.readLine())!=null)
{
JSONArray jsa=new JSONArray(line);
for(int i=0;i<jsa.length();i++)
{
JSONObject jo=(JSONObject)jsa.get(i);
title=jo.getString("deal_title"); //tag name "deal_title",will return value that we save in title string
des=jo.getString("deal_description");
}
}
catch(Exeption e){
}
Mention Internet permission in android manifest
Gson library can parse your json string automatically to object.
Simple example:
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};
//(Serialization)
gson.toJson(ints); ==> prints [1,2,3,4,5]
gson.toJson(strings); ==> prints ["abc", "def", "ghi"]
//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
==> ints2 will be same as ints
Here is the code for the Android activity to read from the Web Service and parse the JSON object:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
For more details see http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
you use the json data as follows:
var a=new JSONObject(jsonData);
http://developer.android.com/resources/tutorials/views/hello-mapview.html
Use the data from a to constuct the necessary objects and do the necessary with the same
Related
Spring Controller
#RequestMapping(value = "/login", produces="application/json;charset=UTF-8" ,method = RequestMethod.POST)
#ResponseBody
public int checkLoginInfo(#RequestParam Map<String, String> params) {
User user=new Gson().fromJson((String) params.get("user"), User.class);
return userService.getUserInfo(user);
}
HTML
var params={userid:$("#userid").val(),password:$("#password").val()}
$ajax({method:"post",data:{user:JSON.stringify(params)},url:"foo.bar"});
It worked on website.
But I don't know how to send that Json object for android.
data:{user:JSON.stringify(params)}
I have tested
private static String makeJsonMsg() {
String retMsg = "";
JSONStringer jsonStringer = new JSONStringer();
try {
retMsg = jsonStringer.object()
.key("user").object()
.key("userid").value("userid")
.key("password").value("1234")
.endObject()
.endObject().toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retMsg;
}
like that,
But return 500 error.
Do I need to add header or something else?
The simple way
public void postData(String url,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
How to use
JSONObject requestObject = new JSONObject();
requestObject.put("userid", email);
requestObject.put("password", password);
postData("http://your/login/url",requestObject)
For more info check How to send a JSON object over Request with Android?. Credit of the postData method is for #Sachin Gurnani answer
Hope this helps!!
How can I create this JSON using ArrayList for posting json in Android
{
"user" :
{
"nickname" : "nickname6",
"password" : "1234",
}
}
I get only to a flat JSON
ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nickname","nickname6"));
nameValuePairs.add(new BasicNameValuePair("password", "1234"));
You need to create a JSON, and for that you have to add that JSON as a parameter in your POST method. To do that you can try this :
JSONObject json = new JSONObject(jsonString);
JSONObject joParams = json.getJSONObject("params");
String nickname = joParams.getString("nickname");
post.add(new BasicNameValuePair("nickname", nickname);
As you know, HttpClasses, NameValuePair and BasicNameValuePair have been deprecated in latest android. we should avoid it now.
and If you want to create
{
"user":{
"nickname":"nickname6"
"password":"1234",
}
}
Than you can use below code sample to create the same json using JSONObject class.
JSONObject jObj = new JSONObject();
try {
JSONObject userCredentials = new JSONObject();
userCredentials.put("nickname","nickname6");
userCredentials.put("password","1234");
jObj.put("user", userCredentials);
} catch(Exception e) {
e.printStackTrace();
}
try to use ContentValues like this way
ContentValues values=new ContentValues();
values.put("username",name);
values.put("password",password);
OR
Use MultipartEntity
MultipartEntity multi = new MultipartEntity();
multi.addPart("name", new StringBody("your data"));
multi.addPart("Id", new StringBody("123"));
here's an example for http post using AsyncTask:
public class httpSendrequest extends AsyncTask<Void,Void,String> {
ArrayList<NameValuePair> nvPairs=new ArrayList<>();
Boolean error=false;
#Override
protected void onPreExecute() {
super.onPreExecute();
//here you initialize your json object and add it to value pairs
JSONObject jObj = new JSONObject();
try {
JSONObject userCredentials = new JSONObject();
userCredentials.put("nickname","nickname6");
userCredentials.put("password","1234");
jObj.put("user", userCredentials);
nvPairs.add(new BasicNameValuePair("jsonstring",jObj.toString()));
} catch(Exception e) {
error=true;
}
}
#Override
protected String doInBackground(Void... params) {
if(!error)
try{
String link ="http://"+ip+"/QSystem.asmx/insert_answer" ;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link); //adding URL to the http post
httppost.setEntity(new UrlEncodedFormEntity(nvPairs, HTTP.UTF_8)); //adding the value pairs and encoding to the http post request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
} catch (Exception e){
error=true;
}
return "str";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(!error) {
Toast.makeText(getApplicationContext(), "Sent", Toast.LENGTH_SHORT).show();
}
}
}
then you can call it from onCreate or in an OnClickListener for a button, like this:
new httpSendrequest().execute();
hope this helps :)
I have to send a json string to a server, with this sintax:
"id":"00",
"action":"register",
"get_value":"true",
"values":{
"user":"Jack",
"password":"Jhonson",
"id":"123456"
}
};
I have some problems with the values field, I don't know how to set them in a http request.
can someone makes me an example to how send this json string to a server?
thanks!
try {
JSONObject myObject = new JSONObject();
myObject.put("id", "00");
myObject.put("action", "register");
myObject.put("get_value", "true");
JSONObject values = new JSONObject();
values.put("user", "Jack");
values.put("password", "Jhonson");
values.put("id", "123456");
myObject.put("values",values);
} catch (JSONException e) {
e.printStackTrace();
}
Then use myObject.toString(); to send the content to the server
Please set this json in httpPost.setParams(your_jsonstring);
Prepare Json Object from data :
try{
JSONObject mainJsonObject = new JSONObject();
mainJsonObject.put("id", "00");
mainJsonObject.put("action", "register");
mainJsonObject.put("get_value","true");
JSONObject valueJsonObject = new JSONObject();
valueJsonObject.put("user", "Jack");
valueJsonObject.put("password", "Jhonson");
valueJsonObject.put("id","123456");
mainJsonObject.put("value",valueJsonObject);
}catch (JSONException e){
e.printStackTrace();
}
Add json data to StringEntity as String:
StringEntity se = new StringEntity(mainJsonObject.toString());
Set StringEntity to httpPost :
httpPost.setEntity(se);
01-16 08:16:19.210: W/System.err(1394): org.json.JSONException: Value
{"GetDoctorsListResult":[
{"Name":"Sujay Sharma","DoctorID":154,"Clinics":null,"speciality":"Allergy and immunology","Locality":"Mumbai","Address":"Abcc Building "}
,{"Name":"Samir Tapiawala","DoctorID":159,"Clinics":null,"speciality":"Homeopath","Locality":"Mumbai","Address":"57\/101, Jawahar Nagar RD. NO. 6, GOREGAON WEST "}
,{"Name":"Sahil Kuma","DoctorID":171,"Clinics":null,"speciality":"Aerospace Medicine","Locality":"Mumbai","Address":"Digvija "}
,{"Name":"Himesh Jagtap","DoctorID":180,"Clinics":null,"speciality":"Bariatric Surgery","Locality":"Mumbai","Address":"Abc- Society "}
,{"Name":"Aarnav Prabhudesai","DoctorID":190,"Clinics":null,"speciality":"Dentistry","Locality":"Mumbai","Address":"Joyvilla Jawahar Nagar "}
,{"Name":"Neeharika Saxana","DoctorID":197,"Clinics":null,"speciality":"Gynaecologist","Locality":"Mumbai","Address":"Joyvilla, Jawahar Nagar "}
,{"Name":"Neeharika Saxena","DoctorID":205,"Clinics":null,"speciality":"Gynaecologist","Locality":"Mumbai","Address":"Joyvilla "}
,{"Name":"Ravi Sharma","DoctorID":207,"Clinics":null,"speciality":"Ayurvedacharya","Locality":"Mumbai","Address":"Q\/02 "}
,{"Name":"Prashant Bhatt","DoctorID":209,"Clinics":null,"speciality":"Dentistry","Locality":"Mumbai","Address":"202 Anand Vihar , Bldg No-2 , D-wing , Bhawani Chowk , b--cabin Road , Ambernath(e). Bhawani Chowk"}
,{"Name":"Samidha Sen","DoctorID":210,"Clinics":null,"speciality":"Addiction Medicine","Locality":"Mumbai","Address":"S\/09 "}
,{"Name":"Subodh Mehta","DoctorID":212,"Clinics":null,"speciality":"Orthopaedic Surgery","Locality":"Mumbai","Address":"Opera "}]} of type org.json.JSONObject cannot be converted to JSONArray
here is my activity code:
class DownloadTask extends AsyncTask<String, Void, Object> {
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(4000); // Do your real work here
} catch (InterruptedException e) {
e.printStackTrace();
}
return true; // Return your real result here
}
protected void onPostExecute(Object result) {
// Pass the result data back to the main activity
DoctorSearchActivity.this.data = result;
if (DoctorSearchActivity.this.progressdialog != null) {
DoctorSearchActivity.this.progressdialog.dismiss();
}
try {
JSONStringer geneology = new JSONStringer()
.object().key("Params").object().key("TypesOnSearch")
.value("name").key("CharactersToSearch")
.value("s")
.endObject();
JSONArray results = new JSONArray();
results = BC
.returnJSONArray(geneology,
"http://192.168.2.27/HYEHR_WCFService/DoctorService.svc/GetDoctorsList");
if (results.length() == 0) {
Toast.makeText(
DoctorSearchActivity.this,
"Error Occured while loading data.Try again later.",
Toast.LENGTH_LONG).show();
}
// for (int i = 0; i < results.length(); i++) {
// Log.v("data", results.getString(i));
// }
// aTable = BC.appendRows(aTable, results,
// DoctorSearchActivity.this);
} catch (Exception e) {
// TODO: handle exception
}
}
}
and my json function
:
public JSONArray returnJSONArray(JSONStringer JsonString, String url) {
results = new JSONArray();
try {
HttpPost request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
StringEntity entity = new StringEntity(JsonString.toString());
request.setEntity(entity);
Log.v("data", request + JsonString.toString());
// Log.v("data sender",request.setEntity(entity));
// Send request to WCF service
DefaultHttpClient httpClient1 = new DefaultHttpClient();
HttpResponse response = httpClient1.execute(request);
Log.v("response code", response.getStatusLine().getStatusCode()
+ "");
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
results = new JSONArray(new String(buffer));
Log.v("results length : ", results.length() + "");
}
catch (Exception e) {
// i mean sending data without key
// TODO: handle exception
e.printStackTrace();
}
return results;
}
I am getting this error i am passing data in jsonobject and receiving data in jsonarray.
Try to replace this:
results = new JSONArray(new String(buffer));
by this:
results = new JSONObject(new String(buffer)).getJSONArray("GetDoctorsListResult");
The root element of the JSON from URL is a JSONObject you should first parse it to JSONObject and then
get GetDoctorsListResult which is an array from the object.
I think your First Element of object GetDoctorsListResult is JSON array . So you have to take its value in json array.
REFER THIS THREAD and THIS ONE
JSONArray DoctorsList= jsonResponse.getJSONArray("GetDoctorsListResult");
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jsonObject=new JSONObject(result);
JSONArray jsonArray=jsonObject.getJSONArray("GetDoctorsListResult");
use this code after getting response.
I have got the following objective-c code which does what I need to do for android but have no idea how to go about it. I need to access a php file on a webserver which will return a JSON string (Dictionary I think?). Below is the code I have for the iPhone version:
+ (NSDictionary *)getNewMission:(int)maxID
{
NSString *serverUrl = #"http://www.website.com/api/api.php";
NSString *methodString = [NSString stringWithFormat:#"\"method\":\"getNewItem\",\"max_item_id\":\"%d\"", maxID];
NSString *postStr = [NSString stringWithFormat:#"json={%#,\"key1\":\"%#\",\"key2\":\"%#\"}", methodString, KEY_1, KEY_2];
return [JsonManager handleJSONRequest:postStr baseURL:serverUrl];
}
+ (NSDictionary *)handleJSONRequest: (NSString*)postString baseURL:(NSString*)baseUrl
{
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:baseUrl]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSDictionary *results = [data JSONValue];
[data release];
return results;
}
Where should I be looking to help with replicating this in android? I really don't have any meaningful JSON experience especially not in Java/Android. Any help is appreciated.
Here is the code for the Android activity to read from the Web Service and parse the JSON object:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
For more details see http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php