2013-07-29 88 views
1

我打電話給一個Web服務,並接收這個JSON,但實例化JSONObject類拋出錯誤,因爲你可以看到它包含波斯字符(UTF-8),我不認爲這可能是原因這個問題,Json解析在Android 2

JSON:

{"teriffs": [ 
{"name":"برنز","id":"1000","prices":"3;400000-12;600000"}, 
{"name":"برنز","id":"1000","prices":"3;400000-12;600000"}, 
{"name":"نقره ای","id":"1002","prices":"3;700000-12;1000000"}, 
{"name":"نقره ای","id":"1002","prices":"3;700000-12;1000000"}] 
} 

錯誤:

org.json.JSONException: Value {"teriffs": [{"name":"برنز","id":"1000","prices":"3;400000-12;600000"},{"name":"برنز","id":"1000","prices":"3;400000-12;600000"},{"name":"نقره ای","id":"1002","prices":"3;700000-12;1000000"},{"name":"نقره ای","id":"1002","prices":"3;700000-12;1000000"}]} of type java.lang.String cannot be converted to JSONObject

CODE:

try { 
     JSONStringer requestMsg = new JSONStringer().object().key("Ticket").value(TempUtil.UID).endObject(); 
     char[] c = CallServiceHelper.getCallService(requestMsg, "/WWWServices.svc/GetTeriffs"); 
      if(c!=null){ 
      JSONObject array = new JSONObject(new String(c)); 
       System.out.println(array.toString()); 
       return array; 
        } else { 
          return new JSONObject(); 
        } 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 

+4

你可以分享你的JSON代碼,以便我們可以幫助你在隔離的問題? :) –

+0

什麼是String json的值? –

+0

@SunilMishra。它包含從Web服務加載的JSON。確保它不是空字符串。它包含上面提到的JSON。 – Areff

回答

4

原因是:

某些字符不能使用「的MacRoman」字符編碼進行映射。 請更改編碼或刪除「MacRoman」字符編碼不支持的字符。

編輯

String jsonString = " {\"teriffs\": [{\"name\":\"برنز\",\"id\":\"1000\",\"prices\":\"3;400000-12;600000\"},{\"name\":\"برنز\",\"id\":\"1000\",\"prices\":\"3;400000-12;600000\"},{\"name\":\"نقره ای\",\"id\":\"1002\",\"prices\":\"3;700000-12;1000000\"},{\"name\":\"نقره ای\",\"id\":\"1002\",\"prices\":\"3;700000-12;1000000\"}]}"; 

     try { 

      String UTF8String = new String(jsonString.getBytes("UTF-8")); 

      JSONObject object = new JSONObject(UTF8String); 
      JSONArray array = object.getJSONArray("teriffs"); 
      for(int i=0;i<array.length();i++){ 

       JSONObject jsonObject = array.getJSONObject(i); 
       Log.d("ID", jsonObject.getString("id")); 
       Log.d("NAME", jsonObject.getString("name")); 
       Log.d("PRICES", jsonObject.getString("prices")); 

      } 


     } catch (JSONException e2) { 
      // TODO Auto-generated catch block 
      e2.printStackTrace(); 
     } catch (UnsupportedEncodingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
+0

請問您能更具體嗎? – Areff

+0

請參閱我編輯的答案 –

+1

將您的Json字符串轉換爲UTF-8編碼字符串。 –