I have a app which is connected with web service. I send some data by Json:
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", regId);
jsonObject.put("appId", GlobalConfig.getAPPLICATION_ID());
jsonObject.put("phoneId", 1);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Token",jArrayParam.toString()));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(GlobalConfig.getSendEmail());
httppost.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
// TODO: handle exception
}
How Can I see how looks this json?
I want to server see something like this:
{"Token": [
{
"token": "asdasfasf",
"appId": 8.8,
"phoneId": 142.369,
}
Create json object as:
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", regId);
jsonObject.put("appId", GlobalConfig.getAPPLICATION_ID());
jsonObject.put("phoneId", 1);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
JSONObject finaljsonobj = new JSONObject();
finaljsonobj.put("Token", jArrayParam);
Now finaljsonobj JSON Object look as:
{
"Token": [
{
"token": "asdasfasf",
"appId": 8.8,
"phoneId": 142.369,
}
]
}
Use JSON.stringify(json_object).
Let's assume your JSON is actually valid (It is not) and you have a perfectly functional JSONObject. If you want to see it in the console, you just have to do this:
System.out.println(myAwesomeJSONObject.toString(2));
That 1 refers to the number of indent spaces. I like it with 2 indent spaces, but that's a matter of personal taste and readability.
Related
after running the url i am getting data in the following form
[
{
"user_name": "riz",
"gems_available": "10",
"free_gems": "110"
},
{
"match_name": "ausvsind",
"Match_start_time": "2016-03-27 19:00:56",
"season_name": "Mid-Season"
}
]
now i want to get user_name and all the data but unable to do..i am getting this data in the result after running my app but unable to fetch.below i have my java code.please help me where i am wrong.
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
jsonArray = new JSONArray();
jsonArray.put(jsonObj);
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
String str = jsonArray.toString().replace("[", "");
String str1 = str.replace("]", "");
httppost.setEntity(new StringEntity(str1.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
jsonArray1.put(result);
jsobj = new JSONObject(result);
us1 = jsobj.getString(TAG_USER_NAME);
us2 = jsobj.getString(TAG_GEMS_AVAILABLE);
us3 = jsobj.getString(TAG_GEMS_FREE);
Have a look at Retrofit : it helps you parse JSON into a java POJO automagically and will help you avoid non-differential boilerplate
https://github.com/square/retrofit
When I have to get data from a Json, I always you serialization.
Have a Look at GSON. With it, you have to create model Objects that match the json architecture. After it, you can access all your json attributes easily.
There is another, better way to do this.
Use modern libraries for API calls like Retrofit 2.0 with GSON.
Add Retrofit 2.0 to your project
Read: https://github.com/square/retrofit
Create POJO Object from your JSON
http://www.jsonschema2pojo.org/
select Source type > JSON
select Annotation style > GSON
Create API service interface
Step by step: http://square.github.io/retrofit/
Why are you removing the "[" and "]" characters? Those are part of the JSONArray? If you did not want them there, use a JSONObject instead.
I did not test this, so it will have some issues. Conceptually this should work for you:
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
httppost.setEntity(new StringEntity(jsonObj.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
JSONArray jsonArr = new JSONArray(result);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jobj = jsonArr.getJSONObject(i);
if (jobj.has("user_name"))
{
us1 = jobj.getString("user_name");
}
if (jobj.has("gems_available"))
{
us2 = jobj.getString("gems_available");
}
if (jobj.has("free_gems"))
{
us3 = jobj.getString("free_gems");
}
}
I'm trying to send a json file to remote server. If I try it, using this site:
https://www.hurl.it/ passing a json like this:
it works. But If I try it from my code, I have some trouble.
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONArray list1 = new JSONArray();
list1.add("12345678");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs1.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs1.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This is my json example: I need to create something like this: "json":{"company_id":"1","phones":["555555"],"photo":"/files/clients_photos/tmp/484629825.JPG","name":"sdfsdfdsf","birthdate":"10.02.2014", "email":"sdf#sdf.ff"}
UPD:
I have the following error:
{"status":"error","message":"Customer data is empty!"}
Maybe something is wrong in my json.
UDP:
working code
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONObject joB = new JSONObject();
JSONArray list1 = new JSONArray();
list1.add("258963147");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
org.json.JSONObject jsonqwe;
try {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postP = new ArrayList<NameValuePair>();
postP.add(new BasicNameValuePair("json", JSONValue.toJSONString(obj)));
jsonqwe = operationLink.makeHttpRequest("http://crm.pavlun.info/api/register", "POST", postP);
Log.e("sad", jsonqwe.toString());
}catch(Exception e) {
e.printStackTrace();
}
You're problem is that you're not building a JSON object, but using the map's toString() method, which won't give you a properly formatted JSON object.
Try JSONObject's constructor that takes a map as parameter. And than call toString() on the JSONObject.
Try yo change
Map obj=new LinkedHashMap();
to
JSONObject obj=new JSONObject();
you need to send a JSON value
A more suitable solution would be to build a JSONObject instead of the Map you're using. Something like this:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray phoneNumbers = new JSONArray();
phoneNumbers.add("12345678");
JSONObject obj=new JSONObject();
obj.put("company_id","1");
obj.put("phones", phoneNumbers);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This line will return garbage (as far server is concerned)
nameValuePairs1.toString()
because an ArrayList does implement toString like you are expecting. You should be using JSONArray/JSONObject instead.
In the hurl site example one name valu pair is sent. To send name value pais your content type should be form url encoded. So change:
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
to
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Maybe this will help:
httpPost.setHeader("ENCTYPE","multipart/form-data");
EDIT:
As others already stated do not use a Map but a JSONObject. Then change
httpPost.setEntity(new StringEntity(nameValuePairs1.toString()));
to:
String nameValuPairsText = nameValuePairs.toString();
nameValuPairsText = nameValuPairsText.substring(1, nameValuPairsText.length()-1);
httpPost.setEntity(new StringEntity(nameValuPairsText, "UTF-8"));
I'm parsing a json file but i get this message: org.json.JSONException: End of input at character 0 of
the contetnn of the file is:
Are you sure there is not an empty line at the end of the file? Like this:
[
{
code: "UNLC",
cours_jour: "40 020",
variation: "0.00"
},
{
code: "UNXC",
cours_jour: "7 450",
variation: "0.00"
}
]
<-- Empty line here!
Your JSON Object fields need to be encapsulated by quotes
IE
{
"code": "BOAC",
"cours_jour": "29 000",
"variation": "-1.69"
}
How was the JSON file generated?
--Edit
You can use the below code to download the page to a string and then convert it to a JSONArray and then pull each JSONObject. You cannot run any web requests on the main thread so either extend a new asynctask or thread or runnable to perform the below
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("http://www.impaxis-securities.com/securities/cours-actions/cours.json");
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response;
try {
response = httpclient.execute(httpost, responseHandler);
JSONArray arr = new JSONArray(response);
int arrLength = arr.length();
if(arrLength > 0)
{
for(int i = 0; i < arrLength; i++)
{
JSONObject item = arr.getJSONObject(i);
String code = item.getString("code");
String cours_jour = item.getString("cours_jour");
String variation = item.getString("variation");
//Either insert to a DB or add to an array list and return it
}
}
}
catch (ClientProtocolException e) {
//Issue with web server
}
catch (IOException e) {
//Issue with request
}
catch (JSONException e) {
//ISSUE Parsing JSON from site
}
---Edit
I tested the code and it looks like there is a bug with the JSON plugin/REST service
http://drupal.org/node/1433436
I am trying to send this json to web server:
[{"codemenu":"1","name":"Fried Rice"},
{"codemenu":"2","name":"Hongkong Fried Rice"},
{"codemenu":"3","name":"Special fried Rice"}]
This is the code but it's not working:
HttpPost httppost = new HttpPost("http://10.0.2.2/pnir_restoran/test.php");
JSONObject json = new JSONObject();
try {
// JSON data:
json.put("codemenu", "1");
json.put("name", "friedrice");
json.put("codemenu", "2");
json.put("name", "Hongkong friedrice");
json.put("codemenu", "3");
json.put("name", "Special friedrice");
JSONArray postjson=new JSONArray();
postjson.put(json); //i cant use postjson.add(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
What should I do? Please help me.
You need to use a JSONArray and then put individual JSONObjects inside the array:
// Initialize the JSON Array and your three seperate objects.
JSONArray jsonArray = new JSONArray();
JSONObject jObj1 = new JSONObject();
JSONObject jObj2 = new JSONObject();
JSONObject jObj3 = new JSONObject();
// Put elements in one object at a time and put them in your array.
jObj1.put("codemenu", "1");
jObj1.put("name", "friedrice");
jsonArray.put(jObj1);
jObj2.put("codemenu", "2");
jObj2.put("name", "Hongkong friedrice");
jsonArray.put(jObj2);
jObj3.put("codemenu", "3");
jObj3.put("name", "Special friedrice");
jsonArray.put(jObj3);
Instead of doing all JSON handling manually, you can use Spring Android's RestTemplate module.
Let's say I store a list of names , for eg: "abc","bcd","gdf"... in an array of Strings. I have an Android app that displays each of those values along with a checkbox. I need to convert my String array into a JSON String so that I can store it in a remote database. Right now I am working on localhost with a database created using SQL Server. I need to insert the JSON string values in the database using a web service , preferably SOAP
How should I do this ? Is there any other better way to do so ?
Here is my Android code.
Thanks
In my case this works fine,
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", value1);
jsonObject.put("key2", value2);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("bulkdata",
jArrayParam.toString()));
Log.e("bulkdata", jArrayParam.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("yor remote database url");
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// get response entity
HttpEntity entity = response.getEntity();
Try it. Thnx.
Well, I just tried to show you how to write the String array to JSONObject and JSONArray.
String arr[] = {"1","parth","present","30-82011","Mumbai"};
try {
JSONObject obj=new JSONObject();
obj.put("rollno",new Integer(arr[0]));
obj.put("status",arr[1]);
obj.put("date",arr[2]);
obj.put("place",arr[3]);
System.out.print(obj.toString(1));
JSONArray list = new JSONArray();
list.put(arr[0]);
list.put(arr[1]);
list.put(arr[2]);
list.put(arr[3]);
System.out.print(list.toString(1));
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
var arr:String = com.adobe.serialization.json.JSON.encode(Obj);
var data_projects:Array = stmt.getResult().data;
var b_data:String = com.adobe.serialization.json.JSON.encode(data_projects);
var arr:String = com.adobe.serialization.json.JSON.encode(data_projects);
var arr1:Object = com.adobe.serialization.json.JSON.decode(b_data) as Array;
for(var d:int=0;d<=data_projects.length-1;d++)
{
//Mapping properties of Proxy classes with actual fields
var bbb:Object = new Object;
data.MdId = arr1[d].MD_ID;
data.MdDevId=arr1[d].MD_DEVICE_ID;
data.MdRecId=arr1[d].MD_REC_ID;
data.MdPrjId= arr1[d].MD_PRJ_ID ;
data.MdMbcId = arr1[d].MD_MBC_ID;
data.MdMbcValue= arr1[d].MD_MBC_VALUE;
data.MdParentRecId= arr1[d].MD_MBC_ID;
//below is the create method on the WSDL
ws.Create(data);
}