parse json in android [duplicate]

夙愿已清 提交于 2019-12-13 07:20:57

问题


Possible Duplicate:
JSON Parsing in Android

As I find out I need to use Gson class to parse json to Java object in android. It's quite easy to parse simple varables or array, but I don't know how to parse more complex json string, my json look like this:

{"selected_id":3, "data":[{"id":"3","score":"1534"},{"id":"1","score":"1234"}]}

Can anyone help me how to do this?


回答1:


      //Model class 

    class Model {

         private  String mId ;
          private   String mScore;

         public Model (String id , String score){

             mId = id ;
             mScore= score
         }


      //getter and setter 

    } 

// in your class

    private ArrayLsit getLsit(String str){
      ArrayLsit<Model > list = new  ArrayLsit<Model>();

        // getting JSON string from URL
        JSONObject json = new JSONObject(str);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray("data");

            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString("id");
                String score= c.getString("score");
                list.add(new Model(id ,score))

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

   return list

 }



回答2:


Check out the code..

        Result = jsonObject.getString("data");

        jsonArray = new JSONArray(Result);
        for (int i = 0; i < jsonArray.length(); i++) {
            jsonObject = jsonArray.getJSONObject(i);
            try {
                jsonObject.getString("Id");

            } catch (Exception ex) {
                cafeandbarsList.add(null);
                ex.printStackTrace();
            }
        }

Thanks




回答3:


create to class for json,

Gson gson = new Gson(); Jsondata jsonddata = gson.fromJson(response, Jsondata .class);

===== JsonData.jave

@SerializedName("selected_id")
public String sid;

    @SerializedName("data") 
public List<data> dalalist;

=== data.java

    @SerializedName("id")
public String id;

    @SerializedName("score")
public String score;


来源:https://stackoverflow.com/questions/11186683/parse-json-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!