json, wcf and fractions in string - android

If you check my previous questions, you will see that they are all in some way related to "\" or "/" for Android and why my implementations of code wasn't working when other people's versions were.
I now know why mine wasn't working.
I am developing for a live client who has access to a content management system, from which I am getting the data. Other than the general checks, they can post anything they want to the site.
They are posting sizes in inches; e.g. 5-1/2
It is this, and this alone, which is screwing up my Restful json.
For example, 1 eigth has become
1\\\/8
Currently, I am doing a string rewrite at the WCF point to catch these 'fractions' and turn them into decimal just so I can continue development. But I can't code for every eventuality and Android/Eclipse fails at JSONArray json=new JSONArray(result);
Would appreciate any input on this.
Dave

On reflection, and further investigation, it isn't the escaped fractions causing the problem.
It is something more fundamental.
Will close the question.

I have searched high and wide for an answer to this, and have finally found it.
I will share for anyone else experiencing the same issue:
It is the WCF Rest service.
Learning WCF and Android at the same time led me to believe that the response from WCF should be a String serialized in the Json format.
To do this, a .Net object, array or whatever would go through DataContractJsonSerializer before being returned as a String to Android for further parsing.
Something like this:
Dim stream1 As MemoryStream = New MemoryStream
Dim ser As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(myType))
ser.WriteObject(stream1, myThing)
Dim _json As String = Encoding.UTF8.GetString(stream1.ToArray())
stream1.Close()
return _json
Wrong.
Keep your object, array or whatever and return that instead; WCF will take care of the proper escaping for you.
For example (this is VB);
IService:
<OperationContract()> _
<WebGet(BodyStyle:=WebMessageBodyStyle.WrappedRequest, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json, UriTemplate:="/MyKit/{AccountID}")> _
Function GetKit(ByVal AccountID As String) As MyKit
Service:
Public Function GetKit(ByVal AccountID As String) As MyKit Implements IService1.GetKit
Dim allKit As New MyKit() //Your object
objDal.CommandText = 'run some sql here - or whatever
Using dr As SqlDataReader = "blah"
//populate your object
End Using
Return allKit //return the object, not the string representation of it
End Function
Using DataContractJsonSerializer for sending as Json to Android from WCF effectively 'pre-escapes' the data. When it gets to Android, the Json parser is unable to handle it, because it also escapes the data.

Related

Python json/list to dictionary cast not working

I'm currently deveolping an Android application that has Django framework as it's server side.
When i'm posting a data of a new user to my database i am POSTing a multipart request that has a user part inside.
The user for some reason is represented as a list but when i take it out of the request.data['user'] it's a str instance (Yea i dont know why...)
When i fetch that str i started working on it with json package.
I looked up on the internet (to many places..) how to convert a string in json format to a dictionary.
What i found is that when you use the json.loads command it doesn't give a dict back but a str instance :)
This is the code on my server side when i enter the create function of the ModelViewSet that handles the creation of the user.
userJson = request.data['user']
userJson = json.dumps(userJson)
userJson = json.loads(userJson)
What i tried to do is to make a string of my own in JSON format and that called the json.loads() command which gave me the dict object..
There seems to be a problem with processing the str from the http request of django rest framework for some reason or there's something else i am not seeing.
I tried the following links -
Converting JSON String to Dictionary Not List
http://docs.python-guide.org/en/latest/scenarios/json/
Didn't worked also..
Now, i tried accessing the str i got from json.loads() like a dictionary in this way.
id = userJson['id']
Now lets say maybe i passed a wrong json format to the loads function, it should have thrown an exception..
The code above (getting the id) raised an exception of 'String indices must be integer' - it doesn't convert it to dict! LOL xD
Good note worth mentioning - I'm trying to convert the json to a dictionary so i could access it like this - dictObject['id']
Well i would really appreciate every help!
Thanks :)
For some reason , when i did this commands-
userJson = request.data['user']
userJson = json.loads(userJson)
userJson = json.loads(userJson)
What i got to have inside the userJson after the second json.loads(userJson) I got the actual dict object to the userJson member.
Appearently it is a bug.
21 January - another update, I truly was doing double Json encoding on the Android application so that was the reason for double json. loads()

Split list information coming from tornado web-service

I have a Tornado web service that returns a list to an android application as below
output = []
output.append(img_URL)
output.append(temp_folder_name)
self.finish(output)
First it assigns values to a list called "output" and then return it.
My question is how can I split this data within the Android application, I have the following two lines of code within the Android application
HttpEntity responseEntity = httpResponse.getEntity();
String transformedImageURL = EntityUtils.toString(responseEntity);
but when I try to output it (using Toast) the android application force closes. Could you please suggest me a better solution for this.
Thank you for your time.
The data between python and android will not full translate well unless you use a message passing convention. I would suggest rolling this data into lets say into JSON. Like this
output = []
output.append(img_URL)
output.append(temp_folder_name)
self.set_header("Content-Type", "application/json")
from json import dumps
self.finish(dumps(output))
On android side of things, you can use JSON library to parse data.

Ajax post data in android java

I am new t ajax, but quite familiar with android. I am converting a ajax program to android app. As a part of it, i need to post data to the server. Below is the given post command in ajax.
var postTo = 'xyz.php';
$.post(postTo,{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' } ,
function(data) {
if(data.success){
window.localStorage["sa_id"] = data.mid;
window.location="getempdb.html";
}
if(data.message) {
$('#output').html(data.message);
} else {
$('#output').html('Could not connect');
}
},'json');
I want to implement this in android but under very little from the above statements. Could anyone who is good at ajax help me out with this thing. As of now, i get the user name and telephone number as a edit text input. I need to send this to php using http client. I know how to send data using php, but do not know what format to send and whether its a string to send or as a json object to send. Please help in interpreting the above code and oblige.
Apparently, this uses UrlEncodedFormEntity if you are using HttpClient in android.
This is created by using a List of NameValuePair.
from the parameters to the $.post:
{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' }
You have to create a NameValuePair for employee_name, one for phone ... each of which is fetched from a HTML element name employee_name, phone ... This is where you put the values from your EditTexts.
It returns a JSON formatted String, which you have to parse (typically using JSONObject obj = new JSONObject(result); once you have fetched the result from the server)
In this JSON object, you have a key named success, which format is not specified, except you can assume things went well if it is present ; a key mid, and a key message.

Accessing an object from JSON in Android

I have a question that I am a little bit confused about. I am quite new to JSON and getting JSON values in the android API. I am trying to access an array within the response I get. the JSON code I am getting is something like this:
Response:
{
"event": {
"participants": []
},
"status": "success"
}
How would I access the participants array and store their values. This is what I am trying at the moment... but I dont appear to be getting what I want.
try{
//get the JSON values from the URL.
JSONObject json = jParser.getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
} catch(JSONException e) {
}
The thing I am mostly confused about is... what is the arrays type equivalent to. Any advice or reasoning as to the correct way to get ahold of that variables value would be great... thanks guys.. :).
Think JSON is really just a key-value pairing. The JSONArray type is just an array full of objects (like Object[]) - it has no idea what the objects it contains are or what they're to be used for. Its up to you to assign meaning to the JSON stream based on what you know of the source. From what I see of your code, most of it looks fine, though I don't know what your jParser.getJSONFromURL() is doing. Typically, you would build the JSON from the response string like so:
String jsonString = getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
JSONObject json = new JSONObject(jsonString)
JSONObject json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
You can iterate through the array like any other array to get subobjects or whatever:
for(int i=0; i < json_array_participants.getLength(); i++) {
JSONObject participant = json_array_participants.getJSONObject(i);
// Do stuff
}
As a side note - I WOULDN'T use GSON until you understand the underlying protocol, at least a little - because you never know when you might want to parse your JSON from a different language for some reason.
I would strongly recommend to use gson instead as your preferred parser since it will do all the job of serializing and deserializing for you except creating the domain objects.
This tutorial should get you going:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This will depend on what the server is supposed to return. It could be an array of anything and if this is a public service, there should be a specification to go off of.
If you are in charge of the server portion as well, and you have a backing object, Google's GSON library is extremely easy to use. It will also keep type information straight.

Json string mutating

I have a .Net WCF Rest service returning Json to be consumed by an Android app.
In debug, the WCF service correctly has the return value (Json) as:
{"BaseLoyaltyPoints":1480,"BonusLoyaltyPoints":0,"BrandId":1414, [etc...] }
Also in debug, when it returns to Notepad, the return value has changed to:
{\"BaseLoyaltyPoints\":1480,\"BonusLoyaltyPoints\":0,\"BrandId\":1414, [etc...] }
And when it gets to my Android app, it has become:
{\\"BaseLoyaltyPoints\\":1480,\\"BonusLoyaltyPoints\\":0,\\"BrandId\\":1414, [etc...] }
This is the boilerplate code I am using to serialize the Json:
Dim stream1 As MemoryStream = New MemoryStream
Dim ser As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(FullProduct))
ser.WriteObject(stream1, Me)
Dim _json As String = Encoding.UTF8.GetString(stream1.ToArray())
stream1.Close()
The Android code to get the Json is:
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(getString(R.string.CONST_RestService) + "/json/Product/" + productID);
ResponseHandler<String> handler = new BasicResponseHandler();
result = httpclient.execute(request, handler);
jObject = new JSONObject(result);
What's going on?
Thanks
Dave
The JSON Data needs to be an evaluable JavaScript String - the " character needs to be escaped to \" (the character " as opposed to the String limitor "), and the \ in that expression needs to be escaped as well (because \ also is a special character). So it has been that string all along, it was just printed differently everytime.
Take this JavaScript for an example:
object = JSON.parse("{\"hello\":\"World\"}");
alert(object.hello);
The following is more of a guess than actual knowledge, because I do not know how exactly the classes you used behave, but I think that it's about right.
As you can see, the " characters need to be escaped to \", so your .NET JSON serializer does just that. Everything is fine, interpreting this as JS would work as expected.
Now what is probably going on is that your JSONObject constructor does not expect Strings to be already properly escaped, so it does that itself. To clarify: When you say "with one escape character", you probably mean something like this:
String workingJSONString = "{\"Hello\":\"World\"}"
right? The problem here is that Java has the same escaping rules as JavaScript - this is not what you get from your HTTPRequest, what you get is
String youGotThis = "{\\\"Hello\\\":\\\"World\\\"}"
Because there are literal backslashes in your String, and those need to be escaped as well. I am pretty certain that that is what is going on, and you'd probably either have to tell your .NET JSON serializer not to apply escape rules or find something that constructs a JSONObject from a properly escaped JSON string - or remove the unnecessary escapes yourself.
I hope this helped - but again, I am not fully certain so you should just check out if it actually behaves as I said.

Categories

Resources