Parsing JSON array that contain objects with different attributes with Retrofit

瘦欲@ 提交于 2020-01-06 07:12:09

问题


how can I parse JSON array that contains JSON objects without names and each object have his own attributes in Android with Retrofit2. Json is something like this:

[
{
    "username":"alexruskovski",
    "age":27,
    "active":true
},
{
    "languages":"Java",
    "occupation":"Programming",
    "phone_num":"123456789",
    "email":"asdf@qwe.com"
}
]

And I have my POJO's like this:

user:

   public class User{
      String username;
      int age;
      boolean active;
   }

and here is the data object:

public class Data{
   String languages,
   String occupation;
   String phone_num;
   String email;
}

and this is my main response class:

public class MainResponse{
   User user;
   Data data;
}   

And this is how my Retrofit client getData method is

Call<List<MainResponse>> getData();

回答1:


To parse that response you need the following class

  public class MainResponse{
    String username;
    int age;
    boolean active;
    String languages;
    String occupation;
    String phone_num;
    String email;
}

And your getData method

Call<List<MainResponse>> getData();


来源:https://stackoverflow.com/questions/47075862/parsing-json-array-that-contain-objects-with-different-attributes-with-retrofit

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