I have an android app which send jsonobject to server as follow:
JSONObject jsonParam = new JSONObject();
jsonParam.put("snc", serialClient);
jsonParam.put("code", hashString(pwd + serialClient));
printout = new DataOutputStream(urlConn.getOutputStream());
String str = jsonParam.toString();
byte[] data = str.getBytes("UTF-8");
printout.write(data);
printout.flush();
printout.close ();
And the MVC Controller as follow:
<System.Web.Http.AcceptVerbs("Post")> _
Public Function Android_Index(ByVal data As String) As ActionResult
Dim param As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(data)
For Each p In param
LogEntry(p.Key & vbCrLf & p.Value, 0, "test")
Next
Return RedirectToLocal("/UI/Forbidden")
End Function
But I receive the data as empty-no element object. Please help to find where I am going wrong and how can I fix it?
UPDATE
I have tried to create a MVC class as follow:
Public Class SNC
Public snc As String
Public code As String
End Class
And edit the controller as follow:
Public Function Android_Index(ByVal data As SNC) As ActionResult
LogEntry(data.snc, 0, "test")
LogEntry(data.code, 0, "test")
......
End Function
When the android app tried to send the jsonobject, I can confirm the Android_Index has been hit. So I assume the jsonobject should accepted in the "data" parameter. But both "snc" and "code" are blank string. While I have re-check from the android that both "snc" and "code" which sent as jsonobject is not empty. For now, it seems the problem is in android side. Or the way how mvc should accept is not in correct way?
After hours with nothing, finally I can make it work.
The issue is on java side:
First I have to assign the jsonobject to a key as follow:
JSONObject jsonParam = new JSONObject();
jsonParam.put("snc", serialClient);
jsonParam.put("code", hashString(pwd + serialClient));
String param = "data=" + jsonParam.toString(); //assign jsonParam to identifier
Then set the Content-Type to application/x-www-form-urlencoded.
The post data finally catched correctly by the Controller.
Related
I am working on Retrofit Post but i am getting slashes () when sending data to post method. Here i need to send the complete json object data to post method, so i converted the json object to String . But when sending slashes are appending to request. I also replaced the slashes to empty string but it is not working. Any one please help me.
code:
private void favouriteadding(String restaurant_id, String restaurant_name, JsonArray Restaurant_info) {
String replac = Restaurant_info.toString(); // jsonarray
replac = replac.replace("[", "")
.replace("]", "")
.trim();
Log.v("Tag_replacestring",""+replac);
ServiceClient serviceClient = ServiceUtil.getServiceClient();
JsonObject userfav = new JsonObject();
userfav.addProperty("user_id", m_sharedPreference.getString("userid", ""));
userfav.addProperty("restaurant_id", restaurant_id);
userfav.addProperty("restaurant_name", restaurant_name);
userfav.addProperty("restaurant_info",replac.replace('\\','"') );
Log.v("Tag_postdata",""+userfav);
serviceClient.list_fav(userfav, listfavcallback);
}
Log:
Tag_replacestring: {"status":"enabled","features":"No Alcohol Available","cuisines":"Hyderabadi","Mughlai","Biryani","Chinese","cost":850.0,"createdAt":"2018-03-08 09:26:13","branch_id":"5aa146ce1d41c86e73e11d79","stats":{},"dishes":"Hyderabadi Dum Biryani","Mutton Biryani}
but getting like this with slashes:
Tag_postdata:
{"user_id":"","restaurant_id":"5aa148051d41c86e73e11d7a","restaurant_name":"Hotel Shadab","restaurant_info":"{\"status\":\"enabled\",\"features\":\"No Alcohol Available\",\"cuisines\":\"Hyderabadi\",\"Mughlai\",\"Biryani\",\"Chinese\",\"cost\":850.0,\"createdAt\":\"2018-03-08 09:26:13\",\"branch_id\":\"5aa146ce1d41c86e73e11d79\"
I'm using Retrofit 2 to call API in Android App. I have a API, using POST, which have a String param in Query Tag. I do everything like doc suppose and I test this API successfully in Test Page. I can run another API correctly so the problem is not the way I use Retrofit 2.
Here is my interface:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query("list") String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
Here is my implementation:
ArrayList<String> id = new ArrayList<>();
id.add("4782947293");
JSONArray jsonArray = new JSONArray(id);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("list", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String list = jsonObject.toString();
Log.e(TAG, "list: " + list);
apiInterface.getListFriend(21, list, 1,1,"AHHIGHTJGI").enqueue(new Callback<GetListFriendDataResponse>() {
#Override
public void onResponse(Call<GetListFriendDataResponse> call, Response<GetListFriendDataResponse> response) {
Log.e(TAG, " response code: "+ response.code());
}
#Override
public void onFailure(Call<GetListFriendDataResponse> call, Throwable t) {
}
});
I always get response code: 400 when use this API.
I'm focusing the "list" var. "list" is a JSON text but I wonder if method "jSon.toString()" is right to get a String from a JSONObject, which can using in Retrofit 2. List param form is:{"list":["12332"]} .
Please help me!
Questions
1) Why you are creating JSONObject and JSONArray on your own?
2) You are creating string using whatever you are creating json.
Eg: {list:["123","456"]}
you are trying pass whole json, I think, instead you need to pass just the array of string to the list key.
Request Sending
{
list:["123","456"]
}
suppose the above json is the request you want to send to server
Now, create model class goto http://jsonschema2pojo.org and paste your json and select json and gson at right side and click on preview.
It will show the classes to map you json to model. Use this model class to set the list to the key in your json
I found my problem. The JSON text contains some special character so I need to convert them to URL encode.
Correct request URL like this:
http://54.169.215.161:8080/users/29/add_friend?list=%7B%22list%22%3A%5B%2215536%22%5D%7D&platform=google
By using Retrofit 2, it uses the URL:
http://54.169.215.161:8080/users/29/add_friend?list={%22list%22:[%2215536%22]}&platform=google
So I get Bad Request Response code.
Retrofit 2 also provides method to convert char sequence to URL encode but it 's not enough. So I don't use Retrofit 's convert method by using this code: encode= true.
so my interface is:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query(value = "list",encoded = true) String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
And I manually convert JSON text to URL encode by code:
list = list.replace("{", "%7B");
list=list.replace("]", "%5D");
list=list.replace("[", "%5B");
list=list.replace(":", "%3A");
list=list.replace("}","%7D");
list = list.replace("\"", "%22");
That's all. Now I can get data by using API.
Suggestion: If u have the same problem, check the URL retrofit return in response and compare to correct URL to see special character, which is not converted to URL encode.
I know there's lots of Questions about this, and lots of answers too, however I haven't been able to find a solution to this problem yet, and wondered if anyone had some ideas.
Please note, I'm new to Android and have unfortunately inherited this project from an Android developer that's no longer with us.
Here's what I'm dealing with.
I have an Android App, that calls a web service, and gets a response Stream.
I've tried to use
String ScanString = new Scanner(inStream).useDelimiter("\\A").next();
which seems to work and results in a string as follows
{"RegResponseResult":"{\u000d\u000a \"REGISTERED\": true,\u000d\u000a \"COMPANY_URL\": \"http:\/\/111.222.3.444\/ABC\/XYZ.svc\/\"\u000d\u000a}"}
My Problem is .....
When I try to use JSONObject JSONObj = new JSONObject(ScanString) To Convert the string to a JSONObject, The Resutling Object Only has one nameValuePair.
ie: key=RegResponseResult and value={ "REGISTERED": true, \r\n"COMPANY_URL": "http://111.222.3.444/ABC/XYZ.svc/"\r\n}
}"
How can a jet a JsonObject, ignoring the 'RegResponseResult' , and using the Containing Tags instead, so that it ends up looking like this.
ie: JSONObj =
Key=REGESTERD value=true
Key=COMPANY_URL value=http://111.222.3.444/ABC/XYZ.svc
Thanks so much in advance.
The "RegResponseResult" is string so you may have to re-parse it again to get the inner json object.
String innerJson = JSONObj.getString("RegResponseResult");
JSONObject inner = new JSONObject(innerJson);
Thanks for the ideas.
I ended up changing my webservice, to output a stream instead of a string.
Turns out WCF Adds a bunch of \ to the string, which invalidates it as a Json String.
But returning it as a stream, doesn't result in anything being added.
Here's the Stream builder code for the webservice... if anyone else needs it.
//When Reading the DB in the Iaaa.csv
public Stream RegResponse(String DeviceData)
{
// *****connect to db and call stored proc goes here****
// .................
// read parameters back from cmd object.
DeviceRegisterResponse Response = new DeviceRegisterResponse();
Response.REGISTERED = Convert.ToBoolean(cmd.Parameters["REGISTERED"].Value);
Response.COMPANY_URL = Convert.ToString(cmd.Parameters["COMPANY_URL"].Value);
return GenerateStreamFromString(JsonConvert.SerializeObject(Response, Formatting.None));
}
//When passsing it back from the service in the Iaaa.cs
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "REG/{id}")]
Stream RegResponse(string id);
I have a problem sending Json messages with RabbitMQ using Android.
I have to parse RabbitMQ object to string and bytes to send the message
channel.basicPublish("", Cola_RPC, props, mensaje_parseado.toString().getBytes()); //Mensaje_parseado is the Json
When I recive the message I don't know how to parse into Json again to get the original message.
I try:
String stringJSON = delivery.getBody().toString();
JSONObject respuesta_desparseada = new JSONObject (stringJSON);
But it doesn't work.
Maybe is a noobie question, but I can't reach the soluction on Google.
Thank you in advance.
You need to change this:
String stringJSON = new String(delivery.getBody());
JSONObject respuesta_desparseada = new JSONObject (stringJSON);
You are calling toString() in a byte[] that uses the toString() method from Object.
If you want to see why, you can run this:
String myString = "myTest";
System.out.println(myString);
System.out.println(myString.getBytes());
System.out.println(myString.getBytes().toString());
System.out.println(new String(myString.getBytes()));
i get a JSON response from a web service:
{"CoverageSearchByLatLongResult":{"HasTransmissionAreasWithSignal":true,"SwitchOffArea":
{"OpenForVastApplications":false,"SeperateTileSetUrl":"http:\/\/myswitch.merged.stage.orchard.net.au\/geodatafiles\/SwitchOffArea\/442b8844-3c05-4548-9424-
4fdafc1f3c62\/Seperate","HASStatus":"Future","HASStatement":"<p>The Household Assistance Scheme is not yet available in this switchover area. Eligible households will be sent a letter when the scheme opens in the Sydney area.<\/p>","SwitchOffDate":"31 December 2013","Events":{"MaximumProximity":6.864859435168742,"Items":[{"Name":"Test Event","Time":"Time","Url":"","Date":"Date","Address":"19a Boundary Street, Rushcutter...
so my question is, in android java how to ask for the key: CoverageSearchByLatLongResult
in ObjC in iphone , something like this:
NSDictionary *coverageResult = [response objectForKey:#"CoverageSearchByLatLongResult"];
so basically im parsing a dictionary with a key, but that result i need to put it inside other dictionary,
[correct me if wrong, in java dictionaries are called maps?]
how to do this?
thanks a lot!
You should use the classes in the org.json package:
http://developer.android.com/reference/org/json/package-summary.html
With them you can do things like:
try {
String jsonString = "YOUR JSON CONTENT";
JSONObject obj = new JSONObject(jsonString);
JSONObject anotherObj = obj.getJSONObject("CoverageSearchByLatLongResult");
boolean bool = anotherObj.getBoolean("HasTransmissionAreasWithSignal");
JSONArray jsonArray = obj.getJSONArray("arrayKey");
int i = jsonArray.getInt(0);
} catch (JSONException e) {
e.printStackTrace();
}
Java Maps map keys to values. As an example of their use:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("string key", 1);
map.put("another key", 3);