[英]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:
我需要从某个 URL 中取出一个 JSON 字符串(我已经能够成功地做到这一点)并将其放入一个数组中。 好吧实际上是两个 arrays。 我正在使用的框架在 Python 上运行并返回一个包含列表(Python 中的数组)的字典。 但是,它显示为 JSON object。 这是我将从 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,但问题是 arrays 存储在 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 object 转换为添加到“feedEntry” object 的常规字符串。
将 python 字典映射到 json 数组是……比您预期的要多。 最好将其放入 json object 或从列表开始,该列表可以直接映射到 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 ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.