Jaimin Thakkar
Jaimin Thakkar

Reputation: 78

How to parse below json in Retrofit 2?

{ "status": true, "message": "Welcome jaymin", "data": { "id": 1, "name": "jaymin", "email": "[email protected]", "mobile": "123456" } }

Upvotes: 0

Views: 58

Answers (2)

Jamie Turner
Jamie Turner

Reputation: 81

To phrase your string to a JSONObject you do the following

String jsonString = '{ "status": true, "message": "Welcome jaymin", "data": { "id": 1, "name": "jaymin", "email": "[email protected]", "mobile": "123456" } }'
JSONObject jsonObj = new JSONObject(jsonString)

Then you can retrieve values from the JSONObject like so

String message = jsonObj.get("message") //Message = "Welcome jaymin"

Upvotes: 0

Abhishek Sharma
Abhishek Sharma

Reputation: 281

you can add GsonFactory or can JacksonFactory in creating retrofit service and can use this link http://www.jsonschema2pojo.org/ to create a pojo class through which you can parse data. I have converted your JSON into Gson format java class which you can use in android to parse data.

   -----------------------------------com.example.Data.java----------------------- 
   ------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Data {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("mobile")
@Expose
private String mobile;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}

}
-----------------------------------com.example.FollowersResponse.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class FollowersResponse {

@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private Data data;

public Boolean getStatus() {
return status;
}

public void setStatus(Boolean status) {
this.status = status;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public Data getData() {
return data;
}

public void setData(Data data) {
this.data = data;
}

}

Upvotes: 1

Related Questions