I am creating an app using RetroFit. I am getting the Data from JSON string from URL and populate it in Recycle view using RetroFit.
My Problem
My problem is , when the app executed, it shows the following errors::
E/RecyclerView: No adapter attached; skipping layout E/RecyclerView:
No adapter attached; skipping layout D/Error:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
BEGIN_ARRAY at line 1 column 2 path $
My Checkings
Checked the URL
Checked URL using Browser.. It returns json successfully
I tried hard to resove this problem , But no solution.
I manually ran the json url and JSON data returned successfully. But on program , it is returning errors.
JSON DATA SAMPLE
[
{
"user_id": "59e4897140d1666c6e8b4567",
"post_id": "59eeb10d40d16686168b4567",
"post_url": "http://demo.cogzideltemplates.com/anan/posts/images/22f3fb0b974be4968118a410e0ad48f7.jpg",
"post_type": "image",
"caption": "vvnnk",
"created": 1508815117,
"time_diff": "1 hours ago",
"first_name": null,
"last_name": null,
"user_name": null,
"email": null,
"profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
"category": "New release"
},
{
"user_id": "59e4897140d1666c6e8b4567",
"post_id": "59ee306940d166697f8b4567",
"post_url": "http://demo.cogzideltemplates.com/anan/posts/images/8f81bd77e60e596cf458d42a743897f8.jpg",
"post_type": "image",
"caption": "cutyy",
"created": 1508782185,
"time_diff": "10 hours ago",
"first_name": null,
"last_name": null,
"user_name": null,
"email": null,
"profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
"category": "Super Star"
}
]
Post.java (POJO for JSON)
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Post {
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("post_id")
#Expose
private String postId;
#SerializedName("post_url")
#Expose
private String postUrl;
#SerializedName("post_type")
#Expose
private String postType;
#SerializedName("caption")
#Expose
private String caption;
#SerializedName("created")
#Expose
private Integer created;
#SerializedName("time_diff")
#Expose
private String timeDiff;
#SerializedName("first_name")
#Expose
private Object firstName;
#SerializedName("last_name")
#Expose
private Object lastName;
#SerializedName("user_name")
#Expose
private Object userName;
#SerializedName("email")
#Expose
private Object email;
#SerializedName("profile_pic")
#Expose
private String profilePic;
#SerializedName("category")
#Expose
private String category;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getPostUrl() {
return postUrl;
}
public void setPostUrl(String postUrl) {
this.postUrl = postUrl;
}
public String getPostType() {
return postType;
}
public void setPostType(String postType) {
this.postType = postType;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public Integer getCreated() {
return created;
}
public void setCreated(Integer created) {
this.created = created;
}
public String getTimeDiff() {
return timeDiff;
}
public void setTimeDiff(String timeDiff) {
this.timeDiff = timeDiff;
}
public Object getFirstName() {
return firstName;
}
public void setFirstName(Object firstName) {
this.firstName = firstName;
}
public Object getLastName() {
return lastName;
}
public void setLastName(Object lastName) {
this.lastName = lastName;
}
public Object getUserName() {
return userName;
}
public void setUserName(Object userName) {
this.userName = userName;
}
public Object getEmail() {
return email;
}
public void setEmail(Object email) {
this.email = email;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<Post> post;
public DataAdapter(ArrayList<Post> post) {
this.post = post;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_userId.setText(post.get(i).getUserId());
viewHolder.tv_postId.setText(post.get(i).getPostId());
viewHolder.tv_postType.setText(post.get(i).getPostType());
viewHolder.tv_caption.setText(post.get(i).getCaption());
Picasso.with(viewHolder.tv_postUrl.getContext()).load(post.get(i).getPostUrl()).into(viewHolder.tv_postUrl);
Picasso.with(viewHolder.tv_profilePic.getContext()).load(post.get(i).getProfilePic()).into(viewHolder.tv_profilePic);
viewHolder.tv_timeDiff.setText(post.get(i).getTimeDiff());
viewHolder.tv_category.setText(post.get(i).getCategory());
viewHolder.tv_created.setText(post.get(i).getCreated());
}
#Override
public int getItemCount() {
return post.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_userId,tv_postId,tv_postType,tv_caption,tv_timeDiff,tv_category,tv_created;
ImageView tv_profilePic,tv_postUrl;
public ViewHolder(View view) {
super(view);
tv_userId = (TextView)view.findViewById(R.id.tv_userId);
tv_postUrl = (ImageView) view.findViewById(R.id.tv_postUrl);
tv_postType = (TextView)view.findViewById(R.id.tv_postType);
tv_caption = (TextView)view.findViewById(R.id.tv_caption);
tv_postId = (TextView)view.findViewById(R.id.tv_postId);
tv_timeDiff = (TextView)view.findViewById(R.id.tv_timeDiff);
tv_profilePic = (ImageView)view.findViewById(R.id.tv_profilePic);
tv_category = (TextView)view.findViewById(R.id.tv_category);
tv_created = (TextView)view.findViewById(R.id.tv_created);
}
}
}
JSONResponse.java
public class JSONResponse {
private Post[] post;
public Post[] getPost() {
return post;
}
}
RequestInterface.java
import retrofit2.Call;
import retrofit2.http.GET;
public interface RequestInterface {
#GET("anan/mobile/posts/viewall_Posts")
Call<JSONResponse> getJSON();
}
MainActitvity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<Post> data;
private DataAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://demo.cogzideltemplates.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
System.out.println("enter the url: "+call.request().url());
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getPost()));
adapter = new DataAdapter(data);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
}
These are my classes. Please hekp me to resolve this problem.
change your JSON data sample to JSON object
Like this
{
[
{
"user_id": "59e4897140d1666c6e8b4567",
"post_id": "59eeb10d40d16686168b4567",
"post_url": "http://demo.cogzideltemplates.com/anan/posts/images/22f3fb0b974be4968118a410e0ad48f7.jpg",
"post_type": "image",
"caption": "vvnnk",
"created": 1508815117,
"time_diff": "1 hours ago",
"first_name": null,
"last_name": null,
"user_name": null,
"email": null,
"profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
"category": "New release"
},
{
"user_id": "59e4897140d1666c6e8b4567",
"post_id": "59ee306940d166697f8b4567",
"post_url": "http://demo.cogzideltemplates.com/anan/posts/images/8f81bd77e60e596cf458d42a743897f8.jpg",
"post_type": "image",
"caption": "cutyy",
"created": 1508782185,
"time_diff": "10 hours ago",
"first_name": null,
"last_name": null,
"user_name": null,
"email": null,
"profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
"category": "Super Star"
}
]}
And Change your JSONResponse.java
Like this
public class JSONResponse {
private List<Post> post;
public List<Post> getPost() {
return post;
}
}
Here is the tutorial for parsing JSON Array and JSON Object
Related
I'am trying to parse data to a recyclerview, i had some problems about expecting JSONArray/JSONObject that i fixed with some help, but this moment I am a little bit lost in what to do in the Onresponse, the original - generatePhonesList(response.body()) isnt working.
this is my json and i am trying to parse the data inside the array results[] :
{
"success": true,
"metadata": {
"sort": "POPULARITY",
"total_products": 20,
"title": "Phones & Tablets",
"results": [
{
"sku": "1",
"name": "Samsung Galaxy S9",
"brand": "Samsung",
"max_saving_percentage": 30,
"price": 53996,
"special_price": 37990,
"image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
"rating_average": 5
},
MainActivity (CALL and Recyclerview creation) :
GetPhoneDataService service = RetrofitInstance.getRetrofitInstance().create(GetPhoneDataService.class);
Call<APIReponse> call = service.getAllPhones();
call.enqueue(new Callback<APIReponse>() {
#Override
public void onResponse(Call<APIReponse> call, Response<APIReponse> response) {
generatePhonesList(response.body());
}
#Override
public void onFailure(Call<APIReponse> call, Throwable t) {
Log.e("eee" , "" + t.getMessage());
}
});
}
private void generatePhonesList(List<Result> phonesList){
recyclerView = findViewById(R.id.recyclerView);
adapter = new PhonesAdapter(phonesList,this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
this is the POJO Class's created in jsonschema2pojo :
public class APIReponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("metadata")
#Expose
private Metadata metadata;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
}
2 class
public class MetaData {
#SerializedName("sort")
#Expose
private String sort;
#SerializedName("total_products")
#Expose
private Integer totalProducts;
#SerializedName("title")
#Expose
private String title;
#SerializedName("results")
#Expose
private List<Result> results = null;
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public Integer getTotalProducts() {
return totalProducts;
}
public void setTotalProducts(Integer totalProducts) {
this.totalProducts = totalProducts;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
3 class:
public class Result {
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("name")
#Expose
private String name;
#SerializedName("brand")
#Expose
private String brand;
#SerializedName("max_saving_percentage")
#Expose
private Integer maxSavingPercentage;
#SerializedName("price")
#Expose
private Integer price;
#SerializedName("special_price")
#Expose
private Integer specialPrice;
#SerializedName("image")
#Expose
private String image;
#SerializedName("rating_average")
#Expose
private Integer ratingAverage;
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getMaxSavingPercentage() {
return maxSavingPercentage;
}
public void setMaxSavingPercentage(Integer maxSavingPercentage) {
this.maxSavingPercentage = maxSavingPercentage;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getSpecialPrice() {
return specialPrice;
}
public void setSpecialPrice(Integer specialPrice) {
this.specialPrice = specialPrice;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getRatingAverage() {
return ratingAverage;
}
public void setRatingAverage(Integer ratingAverage) {
this.ratingAverage = ratingAverage;
}
}
You are passing the APIReponse model to the generatePhonesList(List<Result> phonesList) function. You need to pass only the list of results in this function.
Replace this:
generatePhonesList(response.body());
with:
generatePhonesList(response.body().getMetadata().getResults());
Here getMetadata() and getResults() are the getter functions of metadata model and List.
If you pay close attention response.body() will provide you with class APIResponse. But you need is List<Result>. To achieve this, try response.body().getMetadata().getResults()
This should give you the desired output.
Hi in the below code success is false from server while parsing json data.status code is 200 and created.
Login Modules class contains list of strings and GetModuleList contains a list of strings but in the modules is an array it contains a list of objects
LoginModules.java:
public class LoginModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private List<GetLoginModuleList> result;
public List<GetLoginModuleList> getResult() {
return result;
}
public void setResult(List<GetLoginModuleList> result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
GetLoginModuleList.java:
public class GetLoginModuleList {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
#SerializedName("modules")
#Expose
private List<Modules> modules;
public List<Modules> getModules() {
return modules;
}
public void setModules(List<Modules> modules) {
this.modules = modules;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
#SerializedName("mobile_module_version")
#Expose
private String mobile_module_version;
}
GetLoginModulesList.java:
public class GetLoginModuleList {
#SerializedName("login")
private GetLoginList login;
public GetLoginList getLogin() {
return login;
}
public void setLogin(GetLoginList login) {
this.login = login;
}
public List<Modules> getModules() {
return modules;
}
public void setModules(List<Modules> modules) {
this.modules = modules;
}
#SerializedName("modules")
private List<Modules> modules;
}
Modules.java:
public class Modules {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("isEntity")
#Expose
private String isEntity;
#SerializedName("label")
#Expose
private String label;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsEntity() {
return isEntity;
}
public void setIsEntity(String isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
#SerializedName("singular")
#Expose
private String singular;
}
Json response:
{
"success": true,
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
"modules": [
{
"id": "1",
"name": "Calendar",
"isEntity": true,
"label": "Calendar",
"singular": "To Do"
},
{
"id": "2",
"name": "Leads",
"isEntity": true,
"label": "Leads",
"singular": "Lead"
},
]
}
}
Activity.java:
if (response.isSuccessful()) {
LoginModules loginModules = response.body();
String success = loginModules.getSuccess()
.toString();
if (success.equals("true")) {
String result = loginModules.getResult()
.toString();
Log.i("result", ":" + result);
String Userid = loginModules.getResult()
.getUserid();
Log.i("Userid", ":" + Userid);
String Session = loginModules.getResult()
.getSession();
Log.i("Session", ":" + Session);
String Vtiger_version = loginModules.getResult()
.getVtiger_version();
Log.i("Vtiger_version", ":" + Vtiger_version);
String Mobile_module_version = loginModules.getResult()
.getMobile_module_version();
Log.i("Mobile_module_version", ":" + Mobile_module_version);
//List<Modules> modules = new ArrayList<>();
//Gson gson = new Gson();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray("modules");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = null;
try {
jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("id");
Log.i("id", ":" + id);
// String url = jsonobject.getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (username.equals("admin") && pass.equals("Password!1")) {
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG)
.show();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG)
.show();
}
}
}
Some data is missing in your model structure for parsing data.
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
there is a "login" jsonobject in your "result" object. But you missed the "login" element when you parse it. you should create a java class as LoginModel.
public class LoginModel {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
and put login model in your GetModuleList class.
public class GetLoginModuleList {
#SerializedName("login")
#Expose
private LoginModel login;
Generated GSON JAVA classes from JSON Response. I am trying to parse the Address1 and Address from the Address_.java class. It was generated from the JSON response. I am using GSON to parse it and and trying read the value of Address1 and Address2 from it. I tried different ways to parse but attempt was not successful.
AddressList.java
public class AddressList {
#SerializedName("_embedded")
#Expose
private Embedded embedded;
public Embedded getEmbedded() {
return embedded;
}
public void setEmbedded(Embedded embedded) {
this.embedded = embedded;
}
}
Embedded.java
public class Embedded {
#SerializedName("address")
#Expose
private List<Address> address = null;
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
Address.java
public class Address {
#SerializedName("_links")
#Expose
private Links_ links;
#SerializedName("_embedded")
#Expose
private Object embedded;
#SerializedName("customer")
#Expose
private String customer;
#SerializedName("account")
#Expose
private String account;
#SerializedName("address1")
#Expose
private String address1;
#SerializedName("address2")
#Expose
private String address2;
public Links_ getLinks() {
return links;
}
public void setLinks(Links_ links) {
this.links = links;
}
public Object getEmbedded() {
return embedded;
}
public void setEmbedded(Object embedded) {
this.embedded = embedded;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
}
GSON RESPONSE
{
"_links": {
"self": {
"href": "https://xxxxx/xxx/address?where=xxx%20eq%20xx%20and%20customer%20eq%xxxx&page=1&pagesize=50"
}
},
"_embedded": {
"address": [
{
"_links": {
"self": {
"href": "https://xxxx/xxxx/xxxx/xxxx"
}
},
"_embedded": null,
"customer": "12345",
"account": "",
"address1": "111 ABC DR",
"address2": " ",
}
]
},
"totalItems": 1,
"pageSize": 50,
"totalPages": 1,
"currentPage": 1
}
Can someone please help me? Thanks
Thanks GhostCat. I removed the _embedded from the response and the object itself and it started working. It was third party webservices was sending the response with _. It's working now.
Please tell me how i can parse this model, i am a fresher in android. i tried like this way:-
{ "error": false, "response": { "comdata": [{ "id": "35", "address": "Address" }], "empdata": [{ "cid": "33", "comid": "35", "empname": "test", "empdob": "0000-00-00" }, { "cid": "33", "comid": "35", "empname": "test", "empdob": "0000-00-00" }] }
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jObj = new JSONObject(json);
if (jObj.getString("error").equalsIgnoreCase("false")) {
JSONObject object = jObj.getJSONObject("response");
for (int i = 0; i < object.length(); i++) {
JSONArray jsonArray = object.getJSONArray("parentdata");
JSONObject jsonObject = jsonArray.getJSONObject(0);
//Something write here
JSONArray jsonArray1 = object.getJSONArray("childata");
for (int a = 0; a < jsonArray1.length(); a++) {
JSONObject object1 = jsonArray1.getJSONObject(a);
} return "true";
}return "true";
}else{
}
Your JSON is invalid correct JSON will look like this.
{
"error": false,
"response": {
"comdata": [
{
"id": "35",
"address": "Address"
}
],
"empdata": [
{
"cid": "33",
"comid": "35",
"empname": "test",
"empdob": "0000-00-00"
},
{
"cid": "33",
"comid": "35",
"empname": "test",
"empdob": "0000-00-00"
}
]
}
}
You can parse the JSON using below code.
private void parseResponse(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.getBoolean("error")) {
JSONObject response = jsonObject.getJSONObject("response");
JSONArray jsonArray1 = response.getJSONArray("comdata");
List<ComData> comdataList = new ArrayList<>();
for (int i = 0; i < jsonArray1.length(); i++) {
ComData comData = new ComData();
comData.setId(jsonArray1.getJSONObject(i).getString("id"));
comData.setAddress(jsonArray1.getJSONObject(i).getString("address"));
comdataList.add(comData);
}
JSONArray jsonArray2 = response.getJSONArray("empdata");
List<EmpData> empdataList = new ArrayList<>();
for (int i = 0; i < jsonArray2.length(); i++) {
EmpData empData = new EmpData();
empData.setCid(jsonArray2.getJSONObject(i).getString("cid"));
empData.setComid(jsonArray2.getJSONObject(i).getString("comid"));
empData.setEmpname(jsonArray2.getJSONObject(i).getString("empname"));
empData.setEmpdob(jsonArray2.getJSONObject(i).getString("empdob"));
empdataList.add(empData);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Or you can easily parse JSON to POJO using GSON, refer César Ferreira's answer.
Your JSON is invalid you should have it something like this:
{
"error": false,
"response": {
"comdata": [{
"id": "10",
"username": null,
"email": "example#gmail.com"
}],
"empdata": [{
"eid": "33",
"empname": "test",
"empdob": "0000-00-00",
"empgender": "test",
"empphoto": ""
}],
"someData": [{
"eid": "34",
"empname": "test",
"empdob": "0000-00-00",
"empgender": "test",
"empphoto": ""
}]
}
}
The property someData I had to add it so it would be a valid JSON, I don't know if it fits your requirements.
You can use jsonschematopojo to generate a class like this:
Comdatum class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Comdatum {
#SerializedName("id")
#Expose
private String id;
#SerializedName("username")
#Expose
private Object username;
#SerializedName("email")
#Expose
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object getUsername() {
return username;
}
public void setUsername(Object username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Data class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("error")
#Expose
private Boolean error;
#SerializedName("response")
#Expose
private Response response;
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
}
Empdatum Class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import package com.example;
public class Empdatum {
#SerializedName("eid")
#Expose
private String eid;
#SerializedName("empname")
#Expose
private String empname;
#SerializedName("empdob")
#Expose
private String empdob;
#SerializedName("empgender")
#Expose
private String empgender;
#SerializedName("empphoto")
#Expose
private String empphoto;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpdob() {
return empdob;
}
public void setEmpdob(String empdob) {
this.empdob = empdob;
}
public String getEmpgender() {
return empgender;
}
public void setEmpgender(String empgender) {
this.empgender = empgender;
}
public String getEmpphoto() {
return empphoto;
}
public void setEmpphoto(String empphoto) {
this.empphoto = empphoto;
}
}
Response Class
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
#SerializedName("comdata")
#Expose
private List<Comdatum> comdata = null;
#SerializedName("empdata")
#Expose
private List<Empdatum> empdata = null;
#SerializedName("someData")
#Expose
private List<SomeDatum> someData = null;
public List<Comdatum> getComdata() {
return comdata;
}
public void setComdata(List<Comdatum> comdata) {
this.comdata = comdata;
}
public List<Empdatum> getEmpdata() {
return empdata;
}
public void setEmpdata(List<Empdatum> empdata) {
this.empdata = empdata;
}
public List<SomeDatum> getSomeData() {
return someData;
}
public void setSomeData(List<SomeDatum> someData) {
this.someData = someData;
}
}
SomeDatum Class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SomeDatum {
#SerializedName("eid")
#Expose
private String eid;
#SerializedName("empname")
#Expose
private String empname;
#SerializedName("empdob")
#Expose
private String empdob;
#SerializedName("empgender")
#Expose
private String empgender;
#SerializedName("empphoto")
#Expose
private String empphoto;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpdob() {
return empdob;
}
public void setEmpdob(String empdob) {
this.empdob = empdob;
}
public String getEmpgender() {
return empgender;
}
public void setEmpgender(String empgender) {
this.empgender = empgender;
}
public String getEmpphoto() {
return empphoto;
}
public void setEmpphoto(String empphoto) {
this.empphoto = empphoto;
}
}
And Then you can just do something like this:
String jsonString = "Your JSON String";
Gson converter = new Gson();
Data settingsdata = converter.fromJson(jsonString , Data.class);
I am using Retrofit android library and Gson converter to get JSON response from my server,
this is the response. After receiving the response my app is crashing in onCreate()API. Could anyone suggest me what is wrong with below code?
{
"content": [
{
"id": 1,
"title": "Xrp the standard",
"desc": "Hodl till you die",
"createdBy": {
"id": 1,
"username": "1",
"name": "Radovan"
},
"creationDateTime": {
"epochSecond": 1533679200,
"nano": 0
},
"photo": "to_the_moon.jpg",
"tags": "tagovi",
"likes": 12,
"dislikes": 2,
"comments": [
{
"id": 1,
"title": "Bravo nasi",
"desc": "Samo sloga Srbina spasava",
"createdBy": {
"id": 2,
"username": "",
"name": ""
},
"creationDateTime": {
"epochSecond": 1533679200,
"nano": 0
},
"likes": 3,
"dislikes": 4
}
]
}
],
"page": 0,
"size": 30,
"totalElements": 1,
"totalPages": 1,
"last": true
}
This is my Retro client,
public class RetroClient {
private static final String BASE_URL = "http://192.189.0.27:8080/";
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static RestAPI getRestAPI() {
return getRetrofitInstance().create(RestAPI.class);
}
}
This is my rest api call
#GET("api/posts")
Call<Example> getPosts();
My Example class
public class Example {
#SerializedName("content")
#Expose
private List<Content> content;
#SerializedName("page")
#Expose
private Integer page;
#SerializedName("size")
#Expose
private Integer size;
#SerializedName("totalElements")
#Expose
private Integer totalElements;
#SerializedName("totalPages")
#Expose
private Integer totalPages;
#SerializedName("last")
#Expose
private Boolean last;
public Example() {
}
public Example(List<Content> content, Integer page, Integer size, Integer totalElements, Integer totalPages, Boolean last) {
super();
this.content = content;
this.page = page;
this.size = size;
this.totalElements = totalElements;
this.totalPages = totalPages;
this.last = last;
}
//Getters and setters
My Content class (nested array of objects which I need access to, "content" in response)
public class Content {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("desc")
#Expose
private String desc;
#SerializedName("createdBy")
#Expose
private CreatedBy createdBy;
#SerializedName("creationDateTime")
#Expose
private CreationDateTime creationDateTime;
#SerializedName("photo")
#Expose
private String photo;
#SerializedName("tags")
#Expose
private String tags;
#SerializedName("likes")
#Expose
private Integer likes;
#SerializedName("dislikes")
#Expose
private Integer dislikes;
#SerializedName("comments")
#Expose
private List<CommentResponse> comments;
public Content() {
}
public Content(Integer id, String title, String desc, CreatedBy createdBy, CreationDateTime creationDateTime, String photo, String tags, Integer likes, Integer dislikes, List<CommentResponse> comments) {
super();
this.id = id;
this.title = title;
this.desc = desc;
this.createdBy = createdBy;
this.creationDateTime = creationDateTime;
this.photo = photo;
this.tags = tags;
this.likes = likes;
this.dislikes = dislikes;
this.comments = comments;
}
//Getters and setters
and finally, my callback method in onCreate
RestAPI rest_api = RetroClient.getRestAPI();
Call<Example> call = rest_api.getPosts();
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
if( response.isSuccessful()) {
//here, I need to get "content" so I could fill up list in code below,
//tried almost everything, but activity crashes when created
postsList = response.body().getContent();
for(int i = 0; i < postsList.size(); i++) {
Content content = postsList.get(i);
pAdapter.addPost(content);
}
}
else {
int sc = response.code();
switch (sc) {
}
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Add getters and setters for list "content" in Example class and do this "response.body().getContent()" to get the list.
postsList = response.body().getContent();
Your Pojos should implements Parcelable interface
public class Example implements Parcelable {
//your members
}