public class ClassName implements Serializable {
String body;
String id;
List<Object> attachements;
}
我需要将字符串 [{"body":"Body Message","id":"12345","attachments":[]}] 转换为 List 对象。
我尝试使用 ObjectMapper 但失败了
java.lang.IllegalArgumentException:无法构造 ClassName
的实例(尽管至少存在一个 Creator):没有从字符串值反序列化的字符串参数构造函数/工厂方法 ('{"body":"Body Message ","id":"12345","来源":2,"附件":[],}')
[来源:未知;行:-1,列:-1]
是否有任何简单的方法将这些对象映射到原始类。
最佳答案
你可以尝试这样的事情:
new ObjectMapper().readValue("[{\"body\":\"正文消息\",\"id\":\"12345\",\"附件\":[]}]", List.class);
参见https://www.baeldung.com/jackson-collection-array
完整示例:
package com.company;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
List<ClassName> list = new ObjectMapper().readValue("[{\"body\":\"Body Message\",\"id\":\"12345\",\"attachments\":[]}]", List.class);
System.out.println(list.get(0));
}
public static class ClassName implements Serializable {
String body;
String id;
List<Object> attachements;
}
}
关于java - 在 Java 中如何将 String 转换为 List<ClassName>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62384488/