-2

I am geting JSON data getting from web service. Below is my code.

How can I decode the json data?

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

How can I parse it? Thanks.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

3 Answers3

1

You can keep a POJO class. With the data which you are about to get from server. And parse them and save in that object.

Example:

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 Class:

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

Hope this helps.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
0

You can parse JSON using this code:

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();
}
TMH
  • 6,096
  • 7
  • 51
  • 88
Mohammad Rababah
  • 1,730
  • 4
  • 17
  • 32
0

Use this code :-

 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();
}
Biswajit
  • 1,829
  • 1
  • 18
  • 33