现有一个json数据
{ "result":[ { "powerUnitId":1, "powerUnitName":"供电单位1" }, { "powerUnitId":2, "powerUnitName":"供电单位2" } ] }
这个是从服务器里面获取到的数据,但是数据返回result字段对应的类型是动态的,目前返回的是数组
针对此需求:
设计了两个个对象:Response、Result
public class Response<T> { private T result; /// getter setter }
public class Result { private int powerUnitId; private String powerUnitName; /// getter setter }
转换方法:
gson
依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
代码:
String json = "{\"result\":[{\"powerUnitId\":1,\"powerUnitName\":\"供电单位1\"},{\"powerUnitId\":2,\"powerUnitName\":\"供电单位2\"}]}"; Gson gson = new Gson(); Type founderListType = new TypeToken<Response<ArrayList<Result>>>(){}.getType(); Response<Result> o = gson.fromJson(json, founderListType);
fastjson
依赖:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency>
代码:
String json = "{\"result\":[{\"powerUnitId\":1,\"powerUnitName\":\"供电单位1\"},{\"powerUnitId\":2,\"powerUnitName\":\"供电单位2\"}]}"; Response json1 = JSON.parseObject(json, new TypeReference<Response<List<Result>>>(){});
标签:转换,供电,gson,powerUnitId,json,result,数组,Gson,powerUnitName From: https://www.cnblogs.com/u1w2/p/17359539.html