Java 利用ObjectMapper实现json字符串与对象或者数组的转换

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值