开发者

Convert a JSON string to a Java/Python (Jython) object?

So I understand that you can convert JSON strings to strings and handle JSON objects in general through the org.json bundle in Android, but here's my current situation:

I need to take a JSON string from a certain URL (I'm already able to successfully do this) and make it into an array. Well actually two arrays. The framework I'm using runs on Python and returns a dict that contains lists (arrays in Python). However, it is displayed as a JSON object. Here's an example of what I would be getting from the URL to my Java code:

{"keywords": ["middle east", "syria"], "link": [["middle east", "http://www.google.com/#q=middle east"], ["syria", "http://www.google.com/#q=syria"]]}

As you can see, it's a dict of two indices. The first one is "keywords" that has a list and the second one is "link" that contains a list of lists. The two lists (the first one and the second multidimensional one) are what I want to be able to manipulate in Java. I'm aware that you can use JSONArray, but the problem is that the arrays are stored in a Python dict, and my Android application does not properly make a JSONArray. Do you guys have any ideas of how I can handle this? I'm pretty lost. Here is my code for getting the actual JSON string (the URL in the code is not accessible to everyone, it's being served by paste on my machine):

static public void refreshFeed(){
    try{
        String url = "http://192.17.178.116:8080/getkw?nextline="+line;
        line++;
        HttpClient httpclient = new 开发者_StackOverflowDefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response;
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
            
        String input = null;
        try {
            while ((input = reader.readLine()) != null) {
            sb.append(input + "\n");
            }
        } catch (IOException e) {
                e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
         }
        String enter = sb.toString();
        feedEntry add = new feedEntry(enter);
        addNewEntry(add);
        in.close();
        
    } catch(MalformedURLException e){
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Please also note that this is without the JSONString being made into a JSONArray. It simply translates the JSON object into a regular String that is added to a "feedEntry" object.


Mapping a python dict to a json array is ... more work than you'd expect. It'd be better to make it into either a json object or start with a list, which can be mapped straight to a json array. Info on serializing between python and java.

Here's a code example where I create a list structure in Python, and then grab it in an Android application:

#!/usr/bin/python

print "Content-type: text/html\n\n"

import json
from collections import defaultdict

mystuff = list()
mystuff.append( ('1', 'b', 'c', 'd') )
mystuff.append( ('2', 'f', 'g', 'h') )

stufflist = list()

for s in stufflist:
    d = {}
    d['a'] = s[0]
    d['b'] = s[1]
    d['c'] = s[2]
    d['d'] = s[3]
    stufflist.append(d)

print json.write(stufflist)

And in Android:

// Convert the string (sb is a string butter from the http response) to a json array. 
JSONArray jArray = new JSONArray(sb.toString());

for(int i = 0; i < jArray.length(); i++){
    // Get each item as a JSON object. 
    JSONObject json_data = jArray.getJSONObject(i);

    // Get data from object ... 
    Int a = json_data.getInt("a");
    String b = json_data.getString("b");
    String c = json_data.getString("c");
    String d = json_data.getString("d");

    // Do whatever with the data ... 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜