2015-11-06 135 views
1

在响应中,我期望JSON字符串。 但现在我必须为要检索的对象提供一个键。我想要的回应只是简单的{“xx”:“xx”,“xx”:“xx”}格式,没有一个像这样的名字的数组{{“XX”:[“xx”:“xx”]}。我如何获取JSON而不必提供参数。总之,我只想读取我得到的JSON响应,而不必提供参数。Java抽象空json对象

protected JSONObject parseJSONMeth() { 
      JSONObject jsonObject = null; 
      try { 
       jsonObject = new JSONObject(json); 
       users = jsonObject.getJSONArray(JSON_ARRAY); 
       JSONObject jo = users.getJSONObject(0); 
       return jo; 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      return jsonObject; 
     } 

回答

0

你为什么不使用GSON https://sites.google.com/site/gson/gson-user-guide

Gson gson = new GsonBuilder().create(); 
User result = new User(); 
result=(gson.fromJson(json, User .class)); 

并可为用户列表:

private static List<User> getDataFromJson(String json) { 
     Gson gson = new GsonBuilder().create(); 
     List<User> result = null; 

     try { 
      JSONObject posts=new JSONObject(json); 
      result = gson.fromJson(posts.toString(), new TypeToken<List<User>>(){}.getType()); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return result; 
    }