gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 09:14:20 25 4
gpt4 key购买 nike

所以我了解到您可以通过 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"]]}

如您所见,它是两个索引的字典。第一个是包含列表的“关键字”,第二个是包含列表列表的“链接”。这两个列表(第一个和第二个多维列表)是我希望能够在 Java 中操作的。我知道您可以使用 JSONArray,但问题是数组存储在 Python 字典中,而我的 Android 应用程序无法正确生成 JSONArray。你们对我如何处理这个有什么想法吗?我很迷路。这是我获取实际 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();
}

另请注意,这没有将 JSONString 制作成 JSONArray。它只是将 JSON 对象转换为添加到“feedEntry”对象的常规字符串。

最佳答案

将 python 字典映射到 json 数组是……比您预期的更多工作。最好将它变成一个 json 对象或从一个列表开始,它可以直接映射到一个 json 数组。 Info on serializing between python and 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 ...
}

关于java - 将 JSON 字符串转换为 Java/Python (Jython) 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5827615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com