Json解析正确的解决方案

时间:2013-04-05 10:34:58

标签: android

嗨,我只是陷入有线问题。可能我无法正确使用我的想法。

我正在接受Json的回复

{
"Result":[
   "Entertainment",
   "Business",
   "Sports",
   "Technology"]
}

我能够获得第一个值i,e结果值如下  在后执行循环响应中

["Entertainment","Business","Sports","Technology"]

现在问题是我得到的响应是字符串而不是数组。那么我怎么能分别获取这些值。 请尽快帮助

7 个答案:

答案 0 :(得分:2)

  

问题是我得到的响应是字符串而不是数组

=>正如您所说,您正在以String作为响应,那么您只需要使用您获得的响应字符串创建JSONObject,然后使用以下方法从中获取JSONArray:

try{
    JSONObject objJSON = new JSONObject(objResponse);
    JSONArray arrayResponse = objJSON.getJSONArray("Result");

    // iterate through the JSONArray and fetch one by one string
 } catch (JSONException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
 }

答案 1 :(得分:0)

像这样(并且jsonString是来自服务器的源json响应):

JSONObject json = new JSONObject( jsonString );
JSONArray resultArray = json.getJSONArray("Result");

然后简单地遍历resultArrayget()

答案 2 :(得分:0)

您可以从String字符串中获取Results数组的每个JSON值,如下所示: -

JSONObject jsonObj = new JSONObject(jsonString);
JSONArray resultArray = jsonObj.getJSONArray("Result");
for(int i=0;i<resultArray.length();i++){
    System.out.println(resultArray.getString(i)); // Get each String.
}

答案 3 :(得分:0)

你可以像这样解析你的json

try {
        JSONObject obj=new JSONObject("");
        JSONArray arr=obj.getJSONArray("Result");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

答案 4 :(得分:0)

尝试

JSONObject jsonObj = new JSONObject(json);
JSONArray resultArray = jsonObj.getJSONArray("Result");

for(int i=0;i<resultArray.length();i++){  

  JSONObject jsonObj =   resultArray.getJSONObject(i);
  String Entertainment= jObject.getString("Entertainment");
  String    Business= jObject.getString("Business");
  String    Sports = jObject.getString("Sports");
  String Technology = jObject.getString("Technology ");

}

答案 5 :(得分:0)

要解析您的JSONArray并返回ArrayList个字符串,请尝试以下操作:

JSONObject json = new JSONObject(jsonString);
    JSONArray jsonArray = jsonObj.getJSONArray("Result");
    if(jsonArray!= null) {
        ArrayList<String> arrayResult = new ArrayList<String>();
        for(int i=0;i<jsonArray.length();i++){
            arrayResult.add(arrayResult.getString(i));
        }
    }

注意:你应该把它放在 try catch 集团来抓住 JSONException

答案 6 :(得分:0)

我已经解决了这个问题

JSONParser jParser = new JSONParser();
   // getting JSON string from URL
   JSONObject json = jParser.getJSONObjectFromUrl(url);
   Log.e("json is", "--------------"+json);
   programResponse   =   json.getString("Result");
   Log.e("in the post-execute loop", "in the post-execute loop response is"+programResponse);
   JSONArray arrayResponse = new JSONArray(programResponse);
   for(int i = 0; i < arrayResponse.length(); i++){
   //JSONArray innerJsonArray = json.getJSONArray(i);
   String jsonObject = arrayResponse.getString(i);
   System.out.println(jsonObject);
   Log.e("length is", "--------------"+jsonObject);
   programValues.add(jsonObject);
}