Android将JSON字符串解析为字符串数组
我试图解析从web服务器传回的json字符串,并将其转换为键控字符串数组。结果可能看起来像“str[ID]=artist-title” 下面是我用来获取json并开始解析它的代码Android将JSON字符串解析为字符串数组,android,arrays,json,object,Android,Arrays,Json,Object,我试图解析从web服务器传回的json字符串,并将其转换为键控字符串数组。结果可能看起来像“str[ID]=artist-title” 下面是我用来获取json并开始解析它的代码 new Thread(new Runnable() { public void run() { try { try {
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"}}
您试图解析的JSON字符串中存在错误。
{}
中的每个字符串都是一个JSON对象,在提供的字符串中有一个包含另一个项的对象
对象:
{
"item": {
"artist": "Billy Idol",
"requestid": "42207",
"title": "Rebel Yell"
}
}
然后是另一个包含另一个项的对象
{
"item": {
"artist": "Black Sunshine",
"requestid": "42208",
"title": "Once In My Life"
}
}
这是一个无效的JSONString。我建议您使用以下工具:在尝试解析之前验证JSON字符串 修复json之后,正确解析就容易多了。谢谢