如何在android中解码json数据形成api?

时间:2014-12-03 09:02:59

标签: android json

我从Web服务获取JSON数据。以下是我的代码。

如何解码json数据?

{
    "response": [
        {
            "last_name": "Test",
            "id": 279711390,
            "first_name": "Vishnu",
            "sex": 2,
            "photo_50": "https://vk.com/images/camera_50.gif"
        }
    ]
}

我该如何解析它?感谢。

3 个答案:

答案 0 :(得分:1)

您可以保留POJO课程。使用您即将从服务器获取的数据。并解析它们并保存在该对象中。

示例:

JSONObject json= new JSONObject(responseString);  //your response
try {
    JSONArray responseArray = jsonObj.getJSONArray("response");
    for (int i = 0; i < responseArray.length(); i++) {
        // get value with the NODE key
        JSONObject obj = responseArray.getJSONObject(i);
        String lastName =  obj.getString("last_name");
        String firstName =  obj.getString("first_name");
        //same for all other fields in responseArray
        MyResponse myResp = new MyResponse();
        myResp.setFirstName(firstName);
        myResp.setLastName(lastName);
        //set all other Strings
        //lastly add this object to ArrayList<MyResponse> So you can access all data after saving
    }

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

POJO班级:

public class MyResponse{
    public String firstName="";
    public String lastName="";
    //all other fields and getter setters
}

希望这有帮助。

答案 1 :(得分:0)

您可以使用以下代码解析JSON:

str="<The Json>"
try {
    JSONObject jObject=new JSONObject(str);
    JSONArray menuObject = new JSONArray(jObject.getString("response"));
    String lastName;
    for (int i = 0; i<menuObject.length(); i++) {
        lastName=menuObject.getJSONObject(i).getString("last_name").toString();
        ...
    }
catch (JSONException e) {
    e.printStackTrace();
}

答案 2 :(得分:0)

使用此代码: -

 String string = "Your Json"
 try {
 JSONObject jsonObject=new JSONObject(str);
 JSONArray menuObject = new JSONArray(jObject.getJsonArray("response"));
 //no need of for loop because you have only one object in jsonArray.
JSONObject oject = menuObject.getJSONObject(0);
String lastName = object.getString("last_name");
String firstName = object.getString("first_name");
Log.d("User Name", firstName + " " + lastName);
catch (JSONException e) {
e.printStackTrace();
}