json
对象转Json字符串
使用jackson实现java对象转为Json字符串文章来源:https://www.toymoban.com/news/detail-835182.html
引入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
对象转json字符串
Object val = new Object();// val表示java对象
JsonMapper jsonMapper = new JsonMapper();
String jsonString = jsonMapper.writeValueAsString(val);
测试
JsonMapper mapper = new JsonMapper();
String jsonString = mapper.writeValueAsString(c);
System.out.println(jsonString);
-----------运行结果----------
{"color":"red","price":22.22,"brand":"宝马中国"}
json字符串转换为java对象
使用Jackson对象完成转换工作。文章来源地址https://www.toymoban.com/news/detail-835182.html
json字符串转换对象
JsonMapper mapper = new JsonMapper();
类 obj= mapper.readValue(jsonString, 类.class);
测试
JsonMapper mapper = new JsonMapper();
Car car = mapper.readValue(jsonString, Car.class);
============================================
Car(color=red, price=22.22, brand=宝马中国)
到了这里,关于Java入门-java对象与json之间的转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!