【发布时间】:2019-10-15 05:09:10
【问题描述】:
我必须从 servlet 中收到的 JSON 字符串创建 Java 对象 下面是 JSON
[{"name":"name","value":"Shital"},{"name":"email","value":"swankhade@gmail.com"},{"name":"contactno","value":"9920042776"},{"name":"Address","value":"a6 102 Elementa"}]
我试图通过将 [ 替换为 { 和 ] 替换为 } 来更改 JSON,但它给出了一些其他错误。 我遇到异常的杰克逊代码是
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to Article
Enrole enrole = mapper.readValue(json, Enrole.class);
Enroll 类是带有 setter 和 getter 的简单 bean 类
public class Enrole {
private String name;
private String email;
private long contactno;
private String address;
【问题讨论】:
-
看看Using Jackson to deserialize into a Map,Parsing deeply nested JSON properties with Jackson。您需要创建列表类型:
CollectionType collType = mapper.getTypeFactory().constructCollectionType(List.class, Enrole.class)并在readValue方法中使用它:List<Enrole> users = mapper.convertValue(nodes, collType);