json 字符串如何转成相应的类(范型)

String s = "{\n" +
"\t\"respCode\": \"000\",\n" +
"\t\"respMessage\": \"请求成功\",\n" +
"\t\"data\": [\n" +
"\t\t{\n" +
"\t\t\t\"id\": 53,\n" +
"\t\t\t\"date\": \"2020-04-15 00:00:00\",\n" +
"\t\t\t\"fileName\": \"OP_CODE(1).xlsx\",\n" +
"\t\t\t\"uploadPeople\": \"陈永平\",\n" +
"\t\t\t\"uploadDate\": \"2020-04-15 17:58:11\",\n" +
"\t\t\t\"filePath\": \"/opt/app/app/performance/290901/2020-04-15/OP_CODE(1).xlsx\"\n" +
"\t\t},\n" +
"\t{\n" +
"\t\t\"id\": 53,\n" +
"\t\t\"date\": \"2020-04-15 00:00:00\",\n" +
"\t\t\"fileName\": \"OP_CODE(1).xlsx\",\n" +
"\t\t\"uploadPeople\": \"陈永平\",\n" +
"\t\t\"uploadDate\": \"2020-04-15 17:58:11\",\n" +
"\t\t\"filePath\": \"/opt/app/app/performance/290901/2020-04-15/OP_CODE(1).xlsx\"\n" +
"\t}\n" +
"\t]\n" +
"}\n";


  Type type = new TypeToken<Base<List<ParameterizedBean>>>(){}.getType(); //{} TypeToken中的构造方法被protected修饰只能通过子类去创建
  Base b = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().fromJson(s,type); System.out.println(b.toString());

class ParameterizedBean {
int id;
Date date;
Date uploadDate;

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public Date getUploadDate() {
return uploadDate;
}

public void setUploadDate(Date uploadDate) {
this.uploadDate = uploadDate;
}

String fileName;
String uploadPeople;
String filePath;

public int getId() {
return id;
}

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


public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public String getUploadPeople() {
return uploadPeople;
}

public void setUploadPeople(String uploadPeople) {
this.uploadPeople = uploadPeople;
}

public String getFilePath() {
return filePath;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}
}

class Base<T> {
public String code;
public String message;

public T data;


public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getMessage() {
return message;
}

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

public T getData() {
return data;
}

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

猜你喜欢

转载自www.cnblogs.com/huoyufei/p/12751429.html