一、需求:
我们在开发中也会遇到要我们把json格式数据解析好,然后保存到数据库中.方式方法有很多,小编觉得使用fastjson,最容易实现.
二、依赖准备
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.69</version>
</dependency>
三、JSON字符串准备
[
{
"id": "155",
"name": "小米",
"state": "A",
"createTime": "2021-08-25"
},
{
"id": "105",
"name": "小明",
"state": "B",
"createTime": "2021-08-25"
},
{
"id": "115",
"name": "小红",
"state": "B",
"createTime": "2021-08-25"
}
]
四、代码展示
public void jsonToSql(){
//准备要解析的json字符串
String json = "[\n" +
" {\n" +
" \"id\": \"155\",\n" +
" \"name\": \"小米\",\n" +
" \"state\": \"A\",\n" +
" \"createTime\": \"2021-08-25\"\n" +
" },\n" +
" {\n" +
" \"id\": \"105\",\n" +
" \"name\": \"小明\",\n" +
" \"state\": \"B\",\n" +
" \"createTime\": \"2021-08-25\"\n" +
" },\n" +
" {\n" +
" \"id\": \"115\",\n" +
" \"name\": \"小红\",\n" +
" \"state\": \"B\",\n" +
" \"createTime\": \"2021-08-25\"\n" +
" }\n" +
"]";
//2.将字符串转成list集合
List<Test> list = JSONObject.parseArray(json, Test.class);
//3.保存到数据库 ---这里使用mybatis-plus
list.forEach(x -> testMapper.insert(x));
//4.我们直接打印集合看看映射对不对
list.forEach(x -> System.out.println(x));
}
五、结果展示
六、总结
这样就使用fastjson来实现json到实体类的转换,有了实体类我们添加到数据库就很简单了,如果对您有用,期待您的点赞!!