关于json格式字符串解析并用mybatis存入数据库

园子里面找了很多关于json解析后存入数据库的方法,不是太乱,就是没有写完,我下面的主题代码多是受下面两位的启发,请按顺序查看

 http://www.cnblogs.com/tian830937/p/6364622.html,我沿用了这个例子中的json数据格式,多层嵌套。

http://blog.csdn.net/baicp3/article/details/46711067,这个例子虽然是反例,但是引出了JsonArray。方便后续开发。

看完明白上面两个例子后,我们就可以开始了。(注意:没有看懂上面的例子请先看懂,当然,下面的代码复制过去都能用的,最主要是理解)

1.包,请到http://maven.aliyun.com获取,然后复制到pom.xml中

 

2.配置mybatis.xml,文件放在resource文件夹下,关于数据库的连接就不多讲,照代码中做就是

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:util="http://www.springframework.org/schema/util"xmlns:jpa="http://www.springframework.org/schema/data/jpa"xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"><!-- 配置连接mysql --><!-- 已测试 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/(数据库名)?useUnicode=true&amp;characterEncoding=utf8"/><!-- localhost:3307 -->                                                        <property name="username" value="root"/><property name="password" value="123456"/></bean>    <!-- 配置MyBatis mapper接口扫描 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mapperLocations" value="classpath:(mapper文件夹名)/*.xml"/></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--  <property name="sqlSessionFactory" ref="sqlSessionFactory"/>  --><property name="basePackage" value="(项目dao层的位置,如:xxx.xxx.dao)"/>
</bean>
</beans>

3.设计实体类(实体类是按照要解析的json数据确定的)

student实体类

package com.bean;import java.util.Map;public class Student {private int age;//年龄private String gender;//性别,male/femaleprivate String grades;//班级private String name;//姓名private Map<String, Double> score;//各科分数private String scoreId;private Double weight;//体重public Student() {	// TODO Auto-generated constructor stub}public Student(int age, String gender, String grades, String name, String scoreId, Double weight) {super();this.age = age;this.gender = gender;this.grades = grades;this.name = name;this.weight = weight;this.scoreId=scoreId;}public String getScoreId() {return scoreId;}public void setScoreId(String scoreId) {this.scoreId = scoreId;}public Double getWeight() {return weight;}public void setWeight(Double weight) {this.weight = weight;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getGrades() {return grades;}public void setGrades(String grades) {this.grades = grades;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Map<String, Double> getScore() {return score;}public void setScore(Map<String, Double> score) {this.score = score;}@Overridepublic String toString() {return "Student [age=" + age + ", gender=" + gender + ", grades=" + grades + ", name=" + name + ", score="+ score + ", weight=" + weight + "]";}}

Score实体类

package com.bean;public class Score {private String scoreId;private Double Networkprotocol;//网络协议private Double javaEE;private Double Computerbasis;//计算机基础private Double Linuxoperatingsystem;//Linux操作系统private Double networksecurity;//网络安全private Double SQLdatabase;//Sql数据库private Double datastructure;//数据结构public Score() {// TODO Auto-generated constructor stub
    }public Score(String scoreId, Double networkprotocol, Double javaEE, Double computerbasis,Double linuxoperatingsystem, Double networksecurity, Double sQLdatabase, Double datastructure) {super();this.scoreId = scoreId;Networkprotocol = networkprotocol;this.javaEE = javaEE;Computerbasis = computerbasis;Linuxoperatingsystem = linuxoperatingsystem;this.networksecurity = networksecurity;SQLdatabase = sQLdatabase;this.datastructure = datastructure;}public String getScoreId() {return scoreId;}public void setScoreId(String scoreId) {this.scoreId = scoreId;}public Double getNetworkprotocol() {return Networkprotocol;}public void setNetworkprotocol(Double networkprotocol) {Networkprotocol = networkprotocol;}public Double getJavaEE() {return javaEE;}public void setJavaEE(Double javaEE) {this.javaEE = javaEE;}public Double getComputerbasis() {return Computerbasis;}public void setComputerbasis(Double computerbasis) {Computerbasis = computerbasis;}public Double getLinuxoperatingsystem() {return Linuxoperatingsystem;}public void setLinuxoperatingsystem(Double linuxoperatingsystem) {Linuxoperatingsystem = linuxoperatingsystem;}public Double getNetworksecurity() {return networksecurity;}public void setNetworksecurity(Double networksecurity) {this.networksecurity = networksecurity;}public Double getSQLdatabase() {return SQLdatabase;}public void setSQLdatabase(Double sQLdatabase) {SQLdatabase = sQLdatabase;}public Double getDatastructure() {return datastructure;}public void setDatastructure(Double datastructure) {this.datastructure = datastructure;}@Overridepublic String toString() {return "Score [scoreId=" + scoreId + ", Networkprotocol=" + Networkprotocol + ", javaEE=" + javaEE+ ", Computerbasis=" + Computerbasis + ", Linuxoperatingsystem=" + Linuxoperatingsystem+ ", networksecurity=" + networksecurity + ", SQLdatabase=" + SQLdatabase + ", datastructure="+ datastructure + "]";}}

4.配置dao,建立dao接口

package company.order.dao;import com.bean.Score;
import com.bean.Student;public interface TestDao {int addStudent(Student student);int addScore(Score score);
}

5.设计数据库表结构

student表结构

 

score表结构

 

6.配置mapper.xml,注意修改路径

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"><mapper namespace="company.order.dao.TestDao"><!--测试将json解析的数据存入到数据库 --><insert id="addStudent"  parameterType="com.bean.Student">insert into student(age,gender,grades,name,scoreId,weight                    )values(#{age},#{gender},#{grades},#{name},#{scoreId},#{weight}    )</insert><insert id="addScore"  parameterType="com.bean.Score">insert into score(scoreId,Networkprotocol,javaEE,Computerbasis,Linuxoperatingsystem,networksecurity,SQLdatabase,datastructure            )values(#{scoreId},#{Networkprotocol},#{javaEE},#{Computerbasis},#{Linuxoperatingsystem},#{networksecurity},#{SQLdatabase},#{datastructure}    )</insert>
</mapper>

7.上面的准备工作就做好了,然后就是核心业务(模拟的是service业务层)

(1).将json格式字符串解析成想要的数据格式

(2).将数据封装jsonarray

(3).遍历jsonArray,将object数据封装为JSONObject

(4).运用JSONObject.toBean方法,将其封装为实体类对象

(5).写入数据库

import java.util.UUID;import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;import company.order.dao.TestDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;public class Domain {ClassPathXmlApplicationContext ctx;@Beforepublic void init(){ctx=new ClassPathXmlApplicationContext("backstage-mybatis.xml");}/***这个测试的代码相当于service业务层的代码 */@Testpublic void testJson(){TestDao dao=ctx. getBean("testDao", TestDao.class);String jsonstr = "{\"name\":\"三班\",\"students\":[{\"age\":25,\"gender\":\"female\",\"grades\":\"三班\",\"name\":\"露西\",\"score\":{\"网络协议\":98,\"JavaEE\":92,\"计算机基础\":93},\"weight\":51.3},{\"age\":26,\"gender\":\"male\",\"grades\":\"三班\",\"name\":\"杰克\",\"score\":{\"网络安全\":75,\"Linux操作系统\":81,\"计算机基础\":92},\"weight\":66.5},{\"age\":25,\"gender\":\"female\",\"grades\":\"三班\",\"name\":\"莉莉\",\"score\":{\"网络安全\":95,\"Linux操作系统\":98,\"SQL数据库\":88,\"数据结构\":89},\"weight\":55}]}";int strstrat=jsonstr.indexOf("[");int endstrat=jsonstr.lastIndexOf("]")+1;//将数据分成jsonArrayString jsonStr=jsonstr.substring(strstrat, endstrat);//System.out.println(jsonStr);JSONArray jsonArray=new JSONArray();jsonArray =JSONArray.fromObject(jsonStr);for (Object object : jsonArray) {JSONObject jsonObject=JSONObject.fromObject(object);Student studentData=(Student) JSONObject.toBean(jsonObject, Student.class);            //System.out.println(studentData);String ScoreId= UUID.randomUUID().toString();//System.out.println(ScoreId);studentData.setScoreId(ScoreId);//设计ScoreId方便以后关联查询            Student student=new Student(studentData.getAge(), studentData.getGender(), studentData.getGrades(), studentData.getName(), studentData.getScoreId(), studentData.getWeight());//System.out.println(student);int a=dao.addStudent(student);//将学生信息写入到数据库Map<String,Double> Scores= studentData.getScore();//遍历Scores,将单个数据存入到数据库/*map遍历总结* http://www.cnblogs.com/blest-future/p/4628871.html* */Score scoreData=new Score();for (Map.Entry<String , Double> entry : Scores.entrySet()) {//Map.entry<Integer,String> 映射项(键-值对)  有几个方法:用上面的名字entry//entry.getKey() ;entry.getValue(); entry.setValue();//map.entrySet()  返回此映射中包含的映射关系的 Set视图。//System.out.println("key= " + entry.getKey() + " and value= "+ entry.getValue());if(entry.getKey().equals("网络协议")){                                scoreData.setNetworkprotocol(Double.parseDouble(entry.getValue()+""));} if(entry.getKey().equals("JavaEE")){scoreData.setJavaEE(Double.parseDouble(entry.getValue()+""));} if(entry.getKey().equals("计算机基础")){scoreData.setComputerbasis(Double.parseDouble(entry.getValue()+""));} if(entry.getKey().equals("网络安全")){scoreData.setNetworksecurity(Double.parseDouble(entry.getValue()+""));} if(entry.getKey().equals("Linux操作系统")){scoreData.setLinuxoperatingsystem(Double.parseDouble(entry.getValue()+""));} if(entry.getKey().equals("SQL数据库")){scoreData.setSQLdatabase(Double.parseDouble(entry.getValue()+""));} if(entry.getKey().equals("数据结构")){scoreData.setDatastructure(Double.parseDouble(entry.getValue()+""));}}Score score=new Score(ScoreId, scoreData.getNetworkprotocol(), scoreData.getJavaEE(), scoreData.getComputerbasis(), scoreData.getLinuxoperatingsystem(), scoreData.getNetworksecurity(), scoreData.getSQLdatabase(), scoreData.getDatastructure());int b=dao.addScore(score);System.out.println("学生:"+a+";成绩:"+b);}//JSONObject jsonObject = JSONObject.fromObject(jsonStr);//Grades grades = (Grades) JSONObject.toBean(jsonObject, Grades.class);//System.out.println(grades);//System.out.println(grades.getName());//System.out.println(grades.getStudents());
        }
}

 8.结果:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

 

转载于:https://www.cnblogs.com/wx-ym-good/p/7251707.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/400384.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网络软件的组成

在计算机网络系统中&#xff0c;除了各种网络硬件设备外&#xff0c;还必须具有网络软件 1、网络操作系统 网络操作系统是网络软件中最主要的软件,用于实现不同主机之间的用户通信&#xff0c;以及全网硬件和软件资源的共享&#xff0c;并向用户提供统一的、方便的网络接口,便于…

【Hibernate3.3复习知识点二】 - 配置hibernate环境(annotations)

配置文件hibernate.cfg.xml中引入&#xff1a;<mapping class"com.bjsxt.hibernate.Teacher"/> <hibernate-configuration><session-factory><!-- Database connection settings --><property name"connection.driver_class"&g…

室内定位 -- 资料收集

室内定位系列&#xff08;一&#xff09;——WiFi位置指纹&#xff08;译&#xff09;

【51单片机快速入门指南】4.5:I2C 与 TCA6416实现双向 IO 扩展

目录硬知识IO 扩展芯片 TCA6416ATAC6416A 的寄存器IO 输入寄存器IO 输出寄存器IO 反相寄存器IO 方向寄存器TCA6416A 的操作TCA6416A 写数据TCA6416A 读数据TCA6416A 的 IO 输入寄存器硬件布局示例程序TCA6416A.cTCA6416A.h测试程序main.c实验现象普中51-单核-A2 STC89C52 MSP43…

linux/window 下 solr5.1 tomcat7.x 环境搭建即简单功能测试

2019独角兽企业重金招聘Python工程师标准>>> 之所以想使用solr来进行学习&#xff0c;很大一部分原因就是&#xff0c;solr能够在某种程度上提供RESTFUL相关的URL请求连接&#xff0c;可以把它理解为 以搜索引擎为基础的存储服务系统 &#xff0c;由于他的搜索可以是…

【Java基础总结】多线程

1. 实现多线程的两种方式 1 //第一种&#xff1a;继承Thread类&#xff0c;重写run()方法2 class ThreadTest1 extends Thread{3 public void run(){4 String threadName Thread.currentThread().getName();5 for(int i0;i<10;i){6 System…

C++类分号(;)问题

环境&#xff1a;vs2010 问题&#xff1a;今天编代码过程中发现好多很奇怪的错误&#xff0c;我以为昨天调了下编译器才出问题了。搞了好久&#xff0c;代码注释掉很多还是不行,并且错误还一直在变化。问题大概如下&#xff1a; &#xff08;照片上传不了&#xff09; 1.error …

PHP远程连接MYSQL数据库非常慢的解决方法

不知道如何解决&#xff0c;所以把他空间所在的服务器上也装了个MYSQL,才解决问题&#xff0c;今天又有个这个问题&#xff0c;不能也在这服务器上装一个MYSQL吧&#xff0c;Search: PHP远程连接MYSQL速度慢,有时远程连接到MYSQL用时4-20秒不等,本地连接MYSQL正常,出现这种问题…

【51单片机快速入门指南】5:软件SPI

目录硬知识SPI协议简介SPI接口介绍SPI接口连接图SPI数据传输方向SPI传输模式软件SPI程序源码Soft_SPI.cSoft_SPI.h普中51-单核-A2 STC89C52 Keil uVision V5.29.0.0 PK51 Prof.Developers Kit Version:9.60.0.0 上位机&#xff1a;Vofa 1.3.10 源于软件模拟SPI接口程序代码&…

svn搭建本地服务端

使用VisualSVN Server来完成,下载地址:https://www.visualsvn.com/server/download/ 我安装的版本是3.3.1,安装的时候选择了标准版本&#xff0c;另外一个版本需要付费(日志跟踪、VDFS等功能)更多可以参考https://www.visualsvn.com/server/licensing/安装完成之后&#xff0c;…

hdu 4612 边连通度缩点+树的最长路径

思路&#xff1a;将以桥为分界的所有连通分支进行缩点&#xff0c;得到一颗树&#xff0c;求出树的直径。再用树上的点减去直径&#xff0c;再减一 #pragma comment(linker, "/STACK:1024000000,1024000000") #include<iostream> #include<cstdio> #incl…

c++ primer 4.4节练习答案

练习4.13 a) d3.0, i3 b) i3, d3.5 练习4.14 第一个&#xff1a;非法&#xff0c;42是一个右值&#xff0c;右值不能当做左值使用 第二个&#xff1a;返回值总为真 练习4.15 pi是指针类型&#xff0c;不可将int类型指针赋值给int型&#xff0c;可做如下修改 dval ival 0; pi …

详解Ubuntu Server下启动/停止/重启MySQL数据库的三种方式(ubuntu 16.04)

启动mysql&#xff1a; 方式一&#xff1a;sudo /etc/init.d/mysql start 方式二&#xff1a;sudo service mysql start 停止mysql&#xff1a; 方式一&#xff1a;sudo /etc/init.d/mysql stop 方式二&#xff1a;sudo service mysql stop 重启mysql&#xff1a; 方式一…

【51单片机快速入门指南】5.1:SPI与DS1302时钟芯片

目录硬知识DS1302 简介DS1302 使用控制寄存器日历/时钟寄存器DS1302 的读写时序电路设计示例程序DS1302.cDS1302.h测试程序main.c实验现象普中51-单核-A2 STC89C52 Keil uVision V5.29.0.0 PK51 Prof.Developers Kit Version:9.60.0.0 硬知识 摘自《普中 51 单片机开发攻略》…

006_Select.sql查询语句

--创建一个部门表 CREATE TABLE tb2_dapt(DEPTNO INT PRIMARY KEY, --部门编号DNAME VARCHAR(20) NOT NULL, --部门名称LOC VARCHAR(20) NOT NULL --部门地址 ) --插入数据 INSERT INTO tb2_dapt (DEPTNO, DNAME, LOC) VALUES(10,财务部,北京); INSERT INTO tb2_dapt (DEPTN…

【格局视野】三色需求与工作层次

三色需求 人们的社会经济生活本身就是一个互相交换&#xff0c;价值传递的循环&#xff0c;但这个循环有一个核心&#xff0c;这个核心就是社会大众的需求&#xff0c;也可以称为市场需求&#xff0c;围绕这个需求产生了层级递进的需求关系。 第一个层次是蓝色需求 是最基础的社…

关于linux-Centos 7下mysql 5.7.9的rpm包的安装方式

环境介绍>>>>>>>>>>>>>>>>>> 操作系统&#xff1a;Centos 7.1 mysql数据库版本&#xff1a;mysql5.7.9 mysql官方网站&#xff1a;http://www.mysql.com 原文地址&#xff1a;http://www.cnblogs.com/5201351/p/4912614…

【51单片机快速入门指南】5.2:SPI读取 12位ADC XPT2046 芯片

目录硬知识ADC 简介分辨率转换误差转换速率ADC 转换原理逐次逼近型 ADC双积分型 ADCXPT2046 芯片介绍参考电压内部参考电压外部参考电压输入工作模式单端工作模式差分工作模式温度测量电池电压测量压力测量数字接口笔中断输出转换周期16 时钟周期转换数字时序15 时钟周期转换数…

flask中 app.run(host='0.0.0.0', port=5000, debug=False) 不能用外网ip访问的解决办法

pycharm 2018开启debug模式和修改host&#xff1a; 在Pycharm 2018中&#xff0c;如果想要开启debug模式和更改端口号&#xff0c;则需要编辑项目配置。直接在app.run中更改是无效的。示例图如下&#xff1a; 将 app.run() 改成 app.run(debugFalse) 保存文件&#xff0c…

开发第一个spring boot应用

为什么80%的码农都做不了架构师&#xff1f;>>> 我们来用spring boot开发一个简单的“hello world”web应用&#xff0c;使用maven构建。开始之前&#xff0c;先检查你的java与maven的版本&#xff0c;看是否是spring boot1.3支持的版本&#xff1a; $ java -versi…