Android解析String / JSON问题

时间:2011-12-07 11:58:04

标签: android string json

我有一个关于在Android中解析JSON字符串的问题。我正在尝试解析这个JSON:

{
   "error":504,
   "result":"[\"USRL3C4NAEL84727\",\"USR1HZE4UN5289H1\",\"USR46476WQB92M84\",\"USR4ZQ193YGRK782\"]"
}

我实际需要的部分是解析result。我试过这个:

JSONObject jObj = new JSONObject(responseString);
            int error = Integer.parseInt(jObj.optString("error","0"));
            String errorMessage = jObj.optString("result","");
            if(error==504){
                JSONArray savedCodes = jObj.getJSONArray("result");
                for (int i = 0; i < savedCodes.length(); i++) {
                    String returnString = savedCodes.getString(i);
                    Log.e("","returnString : "+returnString);
                }
            }

但它给我一个例外:

org.json.JSONException: Value ["USR9BA13IZG27H93","USRI818369RH919Y","USRWT7612CQV4375","USR7739R644X84A1"] at result of type java.lang.String cannot be converted to JSONArray

所以我猜它不是JSONArray而且我需要知道如何解析结果部分并在最后得到它:

String 1 = USR9BA13IZG27H93
String 2 = USRI818369RH919Y
and etc...

任何解决方案?

3 个答案:

答案 0 :(得分:2)

也许这个Android JSON解析教程会很有用: http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/

答案 1 :(得分:2)

答案 2 :(得分:0)

最简单的方法:

String errorMessage = jObj.optString("result","");
if(error==504){
     String first = errorMessage.replace("[", "");
     String second = first.replace("]", "");
     String third = second.replace("\"", "");
     String[] split = third.split(",");

     for(int i=0;i< split.length;i++)
         Log.e("","SPLIT : "+split[i]);
}