Parse String From Web Service to a Json Object - android

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);

Related

How to retrieve JsonObject data on MVC

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.

Json with RabbitMQ

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()));

Android - Put method of JSONObect add a '\' when find a '/' in a string

I have to send an encrypted password with DES to a WebServer using a JSONObject encapsulated in a POST request. The problem is that, when I do this:
JSONObject jsonLogin = new JSONObject();
try{
jsonLogin.put("username", usernameS);
jsonLogin.put("password", passwordEncrypted);
}catch (JSONException e){
e.printStackTrace();
}
If I print the content of the JSON object with:
System.out.println("JSON to Server = "+jsonLogin);
the result is:
JSON to Server = {"password":"Qxw\/h16PVdE=\n","username":"XXXXXXXX#gmail.com"}
but the correct password is Qxw/h16PVdE=,so the Server doesn't recognize it.
I found some suggestion that indicate to use: string.replaceAll("\/","/");
But I would like to implement a clean solution.
Please give me any suggestions.
I guess you are doing something wrong while encrypting the data. Any way you can use this piece of code to manipulate the string after encryption.
String encryptedPassword = (String) jsonLogin.get("password");
if (!TextUtils.isEmpty(encryptedPassword) && encryptedPassword.endsWith("\n")) {
encryptedPassword = encryptedPassword.substring(0, encryptedPassword.length() - 1);
jsonLogin.put("password", encryptedPassword);
}
According to this answer
How to remove the \n, \t and spaces between the strings in java?
You can call passwordEncrypted.replaceAll("\\n+", ""); before writing value.

how to pass parameters to RESTlet webservice from android?

I've been looking online for how to pass parameters to RESTlet webservice but it seem there are not much tutorial concerning RESTlet.
I would like to send some parameters gathered from a form on my android application (it would be great if i could do this using JSON).
well i solved this
as for the server side
#Post
public JSONArray serverSideFunction(Representation entity)
throws JSONException {
try {
JSONObject req = (new JsonRepresentation(entity)).getJsonObject();
System.out.println(req.getString(/* filed name */));
System.out.println(req.getString(/* filed name */));
/*
* you can retrieve all the fields here
* and make all necessary actions
*/
} catch (IOException e) {
e.printStackTrace();
}
}
as for the Android Side
HttpClient client = new DefaultHttpClient();
String responseBody;
JSONObject jsonObject = new JSONObject();
try{
HttpPost post = new HttpPost(WebService_URL);
jsonObject.put("field1", ".........");
jsonObject.put("field2", ".........");
StringEntity se = new StringEntity(jsonObject.toString());
post.setEntity(se);
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Content-type", "application/json");
Log.e("webservice request","executing");
ResponseHandler responseHandler = new BasicResponseHandler();
responseBody = client.execute(post, responseHandler);
/*
* You can work here on your responseBody
* if it's a simple String or XML/JSON response
*/
}
catch (Exception e) {
e.printStackTrace();
}
I hope this may be of help
In fact, it depends on what you want to do. With REST (see http://en.wikipedia.org/wiki/Representational_state_transfer), there are two ways to pass parameters or data. Before you need to understand some concepts:
Resource: the REST entity by itself.
Representation: corresponds to its state and can be gotten or updated using different HTTP methods. The kind of content is identified using the content type header (media type in Restlet).
Methods: the GET method is used to get the resource state, PUT to update it, POST to create a new resource and specify its state the same time, DELETE to delete a resource.
Restlet provides Java entities for REST elements.
So, after described that, you can see that passing data or parameters depends of your use case:
1°) Do you want to update the resource state? In this case, you will use the content of the request with methods like POST or PUT. The data structure is free from text, JSON, XML or binary... Restlet provides the ClientResource class to execute requests on RESTful applications. It also provides support to build the representation to send and extract data from the one received. In this case, your data gathered from a form will be used to build the representation. Here are some samples:
//Samples for POST / PUT
ClientResource cr = new ClientResource("http://...");
cr.post(new StringRepresentation("test"));
MyBean bean = new MyBean();
(...)
//Jackson is a tool for JSON format
JacksonRepresentation<MyBean> repr
= new JacksonRepresentation<MyBean>(bean);
cr.put(repr);
//Samples for GET
Representation repr1 = cr.get();
bean = (new JacksonRepresentation<MyBean>(repr1, MyBean.class)).getObject();
2°) Do you want to specify parameters on your GET requests (for example to configure data to retreive and so on)? In this case, you can simply add it on the ClientResource, as described below:
ClientResource cr = new ClientResource("http://...");
cr.getReference().addQueryParameter("q", "restlet");
Representation repr = cr.get();
In this case, your data gathered from a form will be used to build the parameters.
Hope it helps you.
Thierry
If you want request with json structure and your response as JSONObject maybe you can do like this in server side:
public class RequestJSON extends ServerRecource{
#Post("json")
public JSONObject testRequest(String entity){
JSONObject request = new JSONObject(entity);
String value1 = request.getString("key1");
int value2 = request.getInt("key2");
return /* your JSONObject response */;
}
}
And your request can be :
{"key1":"value1", "key2":value2}
I hope this can help you

(Android) Seems like my JSON query is getting double encode

I am getting some weird errors with my Android App. It appears that this code is double encoding the JSON string. What should be sent is ?{"email":"asdf#asdf.com","password":"asdf"}
or
?%7B%22email%22:%22.....
what the server is seeing is %257B%2522email%2522:%2522 ....
which means the server sees %7B%22email%22:%22 .....
This confuses the server.
Any ideas why this is happening?
Thank you for your help
//edited to define objects better
Code:
DefaultHttpClient c = new DefaultHttpClient();
if(cookies!=null)
c.setCookieStore(cookies);
JSONObject jso = new JSONObject():
if(loginNotLogout){
jso.put("email", "email#email.com");
jso.put("password", "PassW0RD");
}
URI u = null;
if(loginNotLogout)
u= new URI("HTTP","www.website.com","/UserService",jso.toString(),"");
else
u= new URI("HTTP","www.website.com","/UserService",jso.toString(),"");
HttpGet httpget = new HttpGet(u);
HttpResponse response = c.execute(httpget);
ret.jsonString = EntityUtils.toString(response.getEntity());
what is userData ?
are you getting values from any EditText?
will using getText().toString() with the text from EditText help?
As it turns out, dropping the "www." from the authority field in the URI constructor caused the address string to be encoded correctly.
I am no web expert, but if anyone can explain this I am all ears. or eyes in this case.
--
Andrew

Categories

Resources