-
前言
-
怎么将json数组字符串转成对象list呢?
-
实战
前言
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));
});
}
效果看出解析出结果了。代码很优雅,不用一个字段一个字段的处理。推荐!!!
开通了个微信公众号:
搜索:怒放de每一天
后续可能不定时推送相关文章,期待和大家一起成长!!
完
原文始发于微信公众号(怒放de每一天):gson自定义Type解析json数组字符串
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/106825.html