关于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&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
總結
以上是生活随笔為你收集整理的关于json格式字符串解析并用mybatis存入数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到火烧房子代表什么
- 下一篇: 做梦梦到别人迁坟怎么回事