前言
gson解析很好用。
string转对象,可以用
new Gson().fromJson(jsonString,object.class);
对象转String可以使用
String str = gson.toJson(user);
怎么将json数组字符串转成对象list呢?
比如下面的json。嵌套很深。
要转的字符串
[ { "label": "您的驾驶证类型", "type": "numberfield", "value": "", "required": true, "order": 2, "placeHolder": "", "selectOption": [ { "itemValue": "1", "itemName": "看书" } ] }, { "label": "您当前驾驶车型", "type": "numberfield", "value": "", "required": true, "order": 2, "placeHolder": "", "selectOption": [ { "itemValue": "1", "itemName": "看书" } ] }, { "label": "您当前车辆品牌", "type": "numberfield", "value": "", "required": true, "order": 2, "placeHolder": "", "selectOption": [ { "itemValue": "1", "itemName": "看书" } ] }, { "label": "您当前所在省市", "type": "numberfield", "value": "", "required": true, "order": 2, "placeHolder": "", "selectOption": [ { "itemValue": "1", "itemName": "看书" } ] } , { "label": "海选赛举办城市", "type": "numberfield", "value": "", "required": true, "order": 2, "placeHolder": "", "selectOption": [ { "itemValue": "1", "itemName": "看书" } ] } ]
答: 自定义TypeToken
实战
实体类
CustomFieldDTO /** * 活动自定义字段 */ @NoArgsConstructor @Data public class CustomFieldDTO { @JsonProperty("label") private String label; @JsonProperty("type") private String type; @JsonProperty("value") private String value; @JsonProperty("required") private Boolean required; @JsonProperty("order") private Integer order; @JsonProperty("placeHolder") private String placeHolder; @JsonProperty("selectOption") private List<SelectOptionDTO> selectOption; @NoArgsConstructor @Data public static class SelectOptionDTO { @JsonProperty("itemValue") private String itemValue; @JsonProperty("itemName") private String itemName; } }
自定义typeToken转换
@Test public void testPrintMessage() { Gson gson = new Gson(); //转成json数组 //自定义类型转换 Type type = new TypeToken<List<CustomFieldDTO>>() { }.getType(); //解析 List<CustomFieldDTO> list = gson.fromJson(str, type); //遍历打印 list.parallelStream().forEach((item) -> { logger.info(String.valueOf(item)); }); }
效果
看出解析出结果了。
代码很优雅,不用一个字段一个字段的处理。推荐!!!