我正在尝试解析从Web服务器传回的json字符串,并将其转换为键控字符串数组。结果希望看起来像“str [ID] =艺术家 - 标题”。
这是我用来获取json并开始解析它的代码。
new Thread(new Runnable() {
public void run() {
try {
try {
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet("http://somesite.net/some.php"); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
JSONObject json = new JSONObject(resString);
String[] array = new Gson().fromJson(resString, String[].class);
Log.e("TESTAPP", "SOME RES E " + array.toString());
is.close(); // Close the stream
}
catch (Exception e) {
Log.e("TESTAPP", "SOME Catch Error E " + e.toString());
}
}
catch (Exception e){
Log.e("TESTAPP", "SOME Error" + e.getMessage());
}
}
}).start();
正在使用一些样本json
{"item":{"artist":"Billy Idol","requestid":"42207","title":"Rebel Yell"}}{"item":{"artist":"Black Sunshine","requestid":"42208","title":"Once In My Life"}}{"item":{"artist":"Blackstreet","requestid":"42209","title":"Before I Let You Go"}}{"item":{"artist":"Black Sabbath","requestid":"42210","title":"Time Machine"}}
答案 0 :(得分:1)
您尝试解析的JSON字符串中存在错误。 {}
内的每个字符串都是一个JSON对象,在提供的字符串中有一个包含另一个item
对象的对象:
{
"item": {
"artist": "Billy Idol",
"requestid": "42207",
"title": "Rebel Yell"
}
}
然后只是另一个包含另一个item
对象的对象。
{
"item": {
"artist": "Black Sunshine",
"requestid": "42208",
"title": "Once In My Life"
}
}
这是一个无效的JSONString。我建议你在尝试解析之前使用像http://jsonlint.com/这样的工具来验证你的JSON字符串。