简体   繁体   English

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

[英]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: 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.我需要从某个 URL 中取出一个 JSON 字符串(我已经能够成功地做到这一点)并将其放入一个数组中。 Well actually two arrays.好吧实际上是两个 arrays。 The framework I'm using runs on Python and returns a dict that contains lists (arrays in Python).我正在使用的框架在 Python 上运行并返回一个包含列表(Python 中的数组)的字典。 However, it is displayed as a JSON object.但是,它显示为 JSON object。 Here's an example of what I would be getting from the URL to my Java code:这是我将从 URL 到我的 Java 代码中得到的示例:

{"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.这两个列表(第一个和第二个多维列表)是我希望能够在 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.我知道您可以使用 JSONArray,但问题是 arrays 存储在 Python 字典中,而我的 Android 应用程序无法正确生成 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):这是我获取实际 JSON 字符串的代码(代码中的 URL 并非所有人都可以访问,它是通过粘贴在我的机器上提供的):

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

Please also note that this is without the JSONString being made into a JSONArray.另请注意,这没有将 JSONString 制成 JSONArray。 It simply translates the JSON object into a regular String that is added to a "feedEntry" object.它只是将 JSON object 转换为添加到“feedEntry” object 的常规字符串。

Mapping a python dict to a json array is... more work than you'd expect.将 python 字典映射到 json 数组是……比您预期的要多。 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.最好将其放入 json object 或从列表开始,该列表可以直接映射到 json 数组。 Info on serializing between python and java .有关 python 和 java 之间序列化的信息

Here's a code example where I create a list structure in Python, and then grab it in an Android application:这是一个代码示例,我在 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)

And in Android:在 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 ... 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM