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()));
Related
I want to store a particular value of JSONobject response in one variable.
My JSON response is a string:
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
And from this response I want to retrieve the mobile number.
Can Anyone help?
Your Json is
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
Parse it Easily
JSONObject jsonObject= new JSONObject(json_response);
String mobile= jsonObject.optString("mobile");
Use asynchttpclient library. Its easy to use and parse values.
add this line in app gradle,
compile 'com.loopj.android:android-async-http:1.4.9'
Then,
Let, String s = "{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}";
JSONObject jsonObject = new JSONObject(s);
String username = jsonObject.optString("username");
String mobile = jsonObject.optString("mobile");
String password = jsonObject.optString("password");
You need to do something like the below:
final JSONObject jsonObject = new JSONObject(response);
if (jsonObject.length() > 0) {
String mobile = jsonObject.optString("mobile");
Log.e("TAG", "mobile:"+mobile);
}
I'm wondering what is the difference between using a JSONObject and JSONTokener to parse a JSON string.
I have seen examples where either of these classes were used to parse a JSON string.
For example, I parsed a JSON string like this:
JSONObject object = (JSONObject) new JSONTokener(jsonString).nextValue();
return object.getJSONObject("data").getJSONArray("translations").
getJSONObject(0).getString("translatedText");
But I also see examples where they simply use a JSONObject class (without using JSONTokener) to parse it:
String in;
JSONObject reader = new JSONObject(in);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
I read the description on this page, but still don't really get the difference. Is one better than the other performance wise and when should a JSONTokener be used?
Thanks!
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 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.
Im using JsonObject to parse a response from an API, the problem is that the resulting String have double quotes, how to get string with no quotes?
JsonElement jelement = new JsonParser().parse(response);
JsonObject jobject = jelement.getAsJsonObject();
String authorization = jobject.get("authorization").toString();
Log.d("mensa","parseado jwt :"+authorization);
so my response looks like...
parseado jwt :"eyJ0eXAiOiJKV1QiLCJhbGciO..."
Actual Json response
{
"authorization": "eyJ0eXAiOiJKV1..."
}
what is the right way to parse this string so i dont get it wrapped with double quotes?
I believe you are using GSON library. No need to trim out your result, gson provide methods for that. try this
String authorization = jobject.get("authorization").getAsString();
Refer Gson API Doc : JsonElement
You are getting Object from Json and then converting to String. jobject.get("authorization").toString(); try to get String.
String authorization = jobject.getString("authorization");
Just trim out the quotes: authorization = authorization.substring(1, authorization.length() - 1)
Edit: You should actually use the getString() method as it will return the actual content as a string, however, the above still works as a quick workaround.