關於json格式字符串解析並用mybatis存入數據庫

園子裏面找了不少關於json解析後存入數據庫的方法,不是太亂,就是沒有寫完,我下面的主題代碼可能是受下面兩位的啓發,請按順序查看html

 http://www.cnblogs.com/tian830937/p/6364622.html,我沿用了這個例子中的json數據格式,多層嵌套。java

http://blog.csdn.net/baicp3/article/details/46711067,這個例子雖然是反例,可是引出了JsonArray。方便後續開發。mysql

看完明白上面兩個例子後,咱們就能夠開始了。(注意:沒有看懂上面的例子請先看懂,固然,下面的代碼複製過去都能用的,最主要是理解)linux

1.包,請到http://maven.aliyun.com獲取,而後複製到pom.xml中spring

 

2.配置mybatis.xml,文件放在resource文件夾下,關於數據庫的鏈接就很少講,照代碼中作就是sql

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://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實體類apache

package com.bean;

import java.util.Map;

public class Student {
	  private int age;//年齡
	    private String gender;//性別,male/female
	    private 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;
		}
		@Override
		public String toString() {
			return "Student [age=" + age + ", gender=" + gender + ", grades=" + grades + ", name=" + name + ", score="
					+ score + ", weight=" + weight + "]";
		}


}

Score實體類json

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;
    }
    @Override
    public String toString() {
        return "Score [scoreId=" + scoreId + ", Networkprotocol=" + Networkprotocol + ", javaEE=" + javaEE
                + ", Computerbasis=" + Computerbasis + ", Linuxoperatingsystem=" + Linuxoperatingsystem
                + ", networksecurity=" + networksecurity + ", SQLdatabase=" + SQLdatabase + ", datastructure="
                + datastructure + "]";
    }
    


        
}

4.配置dao,創建dao接口spring-mvc

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;
    @Before
    public void init(){
        ctx=new ClassPathXmlApplicationContext("backstage-mybatis.xml");
    }
    
    /**
     *這個測試的代碼至關於service業務層的代碼 
     */
    @Test
    public 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;
        //將數據分紅jsonArray
        String 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.結果:

 

 

相關文章
相關標籤/搜索