As part of the application we are developing (with android client and Django server) a json object which contains user name and pass word is sent to server from android client as follows
HttpPost post = new HttpPost(URL);
/*Adding key value pairs */
json.put("username", un);
json.put("password", pwd);
StringEntity se = new StringEntity(json.toString());
post.setEntity(se);
response = client.execute(post);
The response is parsed like this
result = responsetoString(response.getEntity().getContent()); //Conv开发者_如何学运维erts response to String
jObject = new JSONObject(result);
JSONObject post = jObject.getJSONObject("post");
username = post.getString("username");
message = post.getString("message");
Hope upto this everything is fine. The problem comes when parsing or sending JSON responses in Django server. Whats the best way to do this?
We tried using SimpleJSON and it turned out not to be so simple as we didn't find any good tutorials or sample code for the same? Are there any python functions similiar to get,put and opt in java for JSON? Any help would be much appreciated..
Python standard library has JSON load/dump facility: http://docs.python.org/library/json.html
In Python, JSON arrays become lists, and JSON objects become dicts. Other than that, logical mappings are used (string -> unicode, true/false -> True/False, null -> None).
simplejson.loads and simplejson.dumps transform strings to/from python dicts
from django.utils import simplejson
result = simplejson.loads('{"username": "abc", "password": "def"}')
# now just use result like a python dictionary
username = result.get('username', None) # pass second parameter as a default
# or catch KeyError
try:
password = result['password']
except KeyError, e:
print 'no password'
dumps is pretty straightforward too:
a_dict = {'username':'abc', 'password': 'def'}
json_str = simplejson.dumps(a_dict)
# json_str = '{"username": "abc", "password": "def"}'
精彩评论