在Python中创建JSON并在Java中解析
我的应用程序需要通过HTTP请求,把JSON数据从一个用Python写的RESTful后端服务器发送到安卓设备。不过,我总是遇到JsonParseException这个错误。下面是我创建和返回JSON的方式:
articleList = []
obj = Content.objects.filter(id = 332).values()[0]
articleList.append(obj)
data = {'articleList' : articleList}
return simplejson.dumps(data)
这个JSON看起来是这样的:
{\"articleList\":
[
{\"ArticleName\": \"Test_ArticleName\\n\", \"ArticleText\":\"Test_ArticleText\"
,\"Author\": \"Test_Author\\n\", \"SourceID\": 18, \"Image\": \"NULL\", \"ImageLink\": \"NULL\", \"Video\": \"NULL\", \"PublicationDate\": \"8/15/2011 4:00AM\", \"VideoLink\": \"NULL\\n\", \"NumViews\": 0, \"Type\": \"NULL\", \"id\": 332}
]
}
当我把这个字符串复制粘贴到Java中时,它可以正常工作,所以我觉得问题可能不在于结构。
在客户端,我使用GSON库来解析这个JSON:
ArticleList articleList;
InputStream source = retrieveStream(urlStr);
Gson gson = new GsonBuilder().setVersion(1.0).create();
String json = convertStreamToString(source);
try {
json = URLDecoder.decode(json,"UTF-8");
articleList = gson.fromJson(json, ArticleList.class);
} catch (UnsupportedEncodingException e1) {
Log.e(TAG,"Decoding error: "+e1);
} catch (JsonParseException e) {
Log.e(TAG, "Parsing error: "+e);
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
Log.i(TAG, sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
我的ArticleList.class里只包含
List<Article> articleList
而我的Article.class里包含所有的键,比如“ArticleName”、“ArticleText”等等。
我遇到的异常是:
Parsing error: com.google.gson.JsonParseException: Expecting object found: "{\"articleList\": [{\"ArticleName\": \"Test_ArticleName\\n\", \"ArticleText\": \"Test_ArticleText\", \"Author\": \"Test_Author\\n\", \"SourceID\": 18, \"Image\": \"NULL\", \"ImageLink\": \"NULL\", \"Video\": \"NULL\", \"PublicationDate\": \"8/15/2011 4:00AM\", \"VideoLink\": \"NULL\\n\", \"NumViews\": 0, \"Type\": \"NULL\", \"id\": 332}
我觉得这个异常可能是因为引号没有正确处理,但我不太确定该怎么解决。我甚至尝试在转换成ArticleList对象之前先解码这个JSON。
1 个回答
2
把你提供的JSON字符串粘贴到Java程序的字符串中是可以的,因为里面的引号(用来表示字符串结束的符号)被转义了。不过,当你从外部资源(比如流、文档等)读取JSON时,这些引号不应该被转义。因此,正确的JSON应该是:
{"articleList":
[
{"ArticleName": "Test_ArticleName\n", "ArticleText":"Test_ArticleText"
,"Author": "Test_Author\n", "SourceID": 18, "Image": "NULL", "ImageLink": "NULL", "Video": "NULL", "PublicationDate": "8/15/2011 4:00AM", "VideoLink": "NULL\n", "NumViews": 0, "Type": "NULL", "id": 332}
]
}