将JSON字符串转换为Java/Python(Jython)对象?

3 投票
1 回答
4180 浏览
提问于 2025-04-16 16:38

我明白在Android中可以通过org.json这个包把JSON字符串转换成字符串,并处理JSON对象,但我现在的情况是这样的:

我需要从一个特定的URL获取一个JSON字符串(我已经成功做到这一点),然后把它变成一个数组。实际上,我需要两个数组。我使用的框架是Python,它返回一个包含列表(在Python中称为数组)的字典。不过,这个字典是以JSON对象的形式显示的。下面是我从URL获取到的内容在Java代码中的样子:

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

如你所见,这里有一个包含两个索引的字典。第一个是“keywords”,它有一个列表;第二个是“link”,它包含一个列表的列表。这两个列表(第一个和第二个多维列表)就是我想在Java中操作的内容。我知道可以使用JSONArray,但问题是这些数组存储在一个Python字典中,而我的Android应用没有正确生成JSONArray。你们有什么建议吗?我有点迷茫。这是我获取实际JSON字符串的代码(代码中的URL并不是所有人都能访问,它是我机器上的一个paste服务):

static public void refreshFeed(){
    try{
        String url = "http://192.17.178.116:8080/getkw?nextline="+line;
        line++;
        HttpClient httpclient = new DefaultHttpClient();
        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();
    }

请注意,这个过程是没有把JSONString转换成JSONArray的。它只是把JSON对象转换成一个普通的字符串,并添加到一个“feedEntry”对象中。

1 个回答

3

把一个Python字典转换成JSON数组其实比你想的要复杂很多。更好的做法是把它变成一个JSON对象,或者直接从一个列表开始,这样就可以直接映射成JSON数组。这里有关于Python和Java之间序列化的信息

下面是一个代码示例,我在Python中创建了一个列表结构,然后在Android应用中获取它:

#!/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)

在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 ... 
}

撰写回答