【问题标题】:Best and simple way to handle JSON in Django在 Django 中处理 JSON 的最佳且简单的方法
【发布时间】:2010-05-17 02:18:18
【问题描述】:

作为我们正在开发的应用程序的一部分(使用 android 客户端和 Django 服务器),一个包含用户名和密码的 json 对象从 android 客户端发送到服务器,如下所示

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

响应是这样解析的

result = responsetoString(response.getEntity().getContent()); //Converts response to String 

jObject = new JSONObject(result);
 JSONObject post = jObject.getJSONObject("post");
    username = post.getString("username");
    message = post.getString("message");

希望一切都好。 在 Django 服务器中解析或发送 JSON 响应时出现问题。最好的方法是什么?

我们尝试使用 SimpleJSON,结果发现并没有那么简单,因为我们没有找到任何好的教程或相同的示例代码?是否有任何类似的 python 函数来获取、放置和选择 java 的 JSON?任何帮助将不胜感激..

【问题讨论】:

    标签: android django json parsing


    【解决方案1】:

    Python 标准库具有 JSON 加载/转储功能: http://docs.python.org/library/json.html

    【讨论】:

      【解决方案2】:

      在 Python 中,JSON 数组变成了列表,而 JSON 对象变成了字典。除此之外,还使用了逻辑映射(字符串 -> unicode,true/false -> True/False,null -> None)。

      【讨论】:

        【解决方案3】:

        simplejson.loads 和 simplejson.dumps 在 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'
        

        转储也很简单:

        a_dict = {'username':'abc', 'password': 'def'}
        json_str = simplejson.dumps(a_dict)
        # json_str = '{"username": "abc", "password": "def"}'
        

        【讨论】:

          猜你喜欢
          • 2010-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-20
          相关资源
          最近更新 更多