Android自己写一个简单的Json转实体类的小框架
1.假设有如下Json
String json1 = "[{\"albumId\": 1,\"id\": 1,\"title\": \"accusamus beatae ad facilis cum similique qui sunt\",\"url\": \"https://via.placeholder.com/600/92c952\",\"thumbnailUrl\": \"https://via.placeholder.com/150/92c952\"},{\"albumId\": 1,\"id\": 2,\"title\": \"reprehenderit est deserunt velit ipsam\",\"url\": \"https://via.placeholder.com/600/771796\",\"thumbnailUrl\": \"https://via.placeholder.com/150/771796\"}]";
2.新建对应的Java实体类
public class Album {
private int albumId;
private int id;
private String title;
private String url;
private String thumbnailUrl;
public Album(int albumId, int id, String title, String url, String thumbnailUrl) {
this.albumId = albumId;
this.id = id;
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}
public Album() {
}
public int getAlbumId() {
return albumId;
}
public void setAlbumId(int albumId) {
this.albumId = albumId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
3.由于这是一个Json数组,所以方法只针对于Json数组,大家可以根据需求自行改动
private <T> List<T> JsonToListObject(String json,Class<T> tClass) throws Exception
{
JSONArray array = new JSONArray(json);
List<T> TList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = new JSONObject(array.optString(i));
T t = tClass.getDeclaredConstructor().newInstance();
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = keys.next();
Field field = tClass.getDeclaredField(key);
field.setAccessible(true);
if (field.getType().equals(int.class))
{
field.set(t,jsonObject.optInt(key));
}
if (field.getType().equals(String.class))
{
field.set(t,jsonObject.optString(key));
}
}
TList.add(t);
}
return TList;
}
4.最后在需要的地方进行调用
try {
List<Album> albums = JsonToListObject(json1, Album.class);
System.out.println(albums);
} catch (Exception e) {
e.printStackTrace();
}