POJO
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestPojo {
String id;
}
测试
@Test
public void test() throws IOException {
TestPojo testPojo1 = new TestPojo("1");
TestPojo testPojo2 = new TestPojo("2");
Set<TestPojo> pojos = new HashSet<>();
pojos.add(testPojo1);
pojos.add(testPojo2);
ObjectMapper mapper = new ObjectMapper();
String pojo1Str = mapper.writeValueAsString(testPojo1);
String pojosStr = mapper.writeValueAsString(pojos);
System.out.println("objString: " + pojo1Str);
System.out.println("objsString: " + pojosStr);
TestPojo convertPojo = mapper.readValue(pojo1Str, TestPojo.class);
System.out.println("convertPojo id: " + convertPojo.getId());
CollectionType setType = mapper.getTypeFactory().constructCollectionType(Set.class, TestPojo.class);
Set<TestPojo> convertPojos = mapper.readValue(pojosStr, setType);
assertEquals(2, convertPojos.size());
System.out.println("convertPojos: " + convertPojos);
Set<TestPojo> converTestPojos = mapper.convertValue(convertPojos, new TypeReference<Set<TestPojo>>() {
});
System.out.println("converTestPojos: " + converTestPojos);
}
结果打印
objString: {"id":"1"}
objsString: [{"id":"1"},{"id":"2"}]
convertPojo id: 1
convertPojos: [TestPojo(id=1), TestPojo(id=2)]
converTestPojos: [TestPojo(id=1), TestPojo(id=2)]
参考
链接: https://stackoverflow.com/questions/28821715/java-lang-classcastexception-java-util-linkedhashmap-cannot-be-cast-to-com-test.