解析json数据,存入数据库 40C

关于json解析存入数据库中的程序

json数据是台风数据,内容从url中获取,这是其中一条:
[{"tfbh":"201611","name":"圆规","ename":"Kompasu","is_current":0,"begin_time":"2016-08-20T08:00:00","end_time":"2016-08-21T14:00:00","land":[]},{"tfbh":"201610","name":"狮子山","ename":"Lionrock","is_current":1,"begin_time":"2016-08-19T20:00:00","end_time":"2016-08-24T08:00:00","land":[]},{"tfbh":"201609","name":"蒲公英","ename":"Mindulle","is_current":0,"begin_time":"2016-08-19T14:00:00","end_time":"2016-08-23T02:00:00","land":[]},{"tfbh":"201608","name":"电母","ename":"Dianmu","is_current":0,"begin_time":"2016-08-18T05:00:00","end_time":"2016-08-19T23:00:00","land":[]},{"tfbh":"201607","name":"灿都","ename":"Chanthu","is_current":0,"begin_time":"2016-08-14T02:00:00","end_time":"2016-08-17T17:00:00","land":[]},{"tfbh":"201606","name":"康森","ename":"Conson","is_current":0,"begin_time":"2016-08-09T08:00:00","end_time":"2016-08-13T14:00:00","land":[]},{"tfbh":"201605","name":"奥麦斯","ename":"Omais","is_current":0,"begin_time":"2016-08-04T14:00:00","end_time":"2016-08-09T20:00:00","land":[]},{"tfbh":"201604","name":"妮妲","ename":"Nida","is_current":0,"begin_time":"2016-07-30T17:00:00","end_time":"2016-08-03T05:00:00","land":[]},{"tfbh":"201603","name":"银河","ename":"Mirinae","is_current":0,"begin_time":"2016-07-26T11:00:00","end_time":"2016-07-28T11:00:00","land":[]},{"tfbh":"201602","name":"卢碧","ename":"Lupit","is_current":0,"begin_time":"2016-07-24T02:00:00","end_time":"2016-07-25T02:00:00","land":[]},{"tfbh":"201601","name":"尼伯特","ename":"Nepartak","is_current":0,"begin_time":"2016-07-03T08:00:00","end_time":"2016-07-10T11:00:00","land":[]}]
要求是解析出数据,插入数据表里,属性有 tfbh(主键),name,ename,begin_time,"is_current",等我是菜鸟,求大神帮忙解答。package service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import dao.TaiFengInfoDao;
import pao.TaiFengInfo;
import net.sf.json.JSONArray;

import net.sf.json.JSONException;

import net.sf.json.JSONObject;

public class getTaifengInfo {
public getTaifengInfo() {}
private static getTaifengInfo dao = new getTaifengInfo();
public static getTaifengInfo getInstance() {
return dao;
}
private static String loadJson (String url) {

StringBuilder json = new StringBuilder();

try {

URL urlObject = new URL(url);

URLConnection uc = urlObject.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

String inputLine = null;

while ( (inputLine = in.readLine()) != null) {

json.append(inputLine);

}

in.close();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return json.toString();

}
/* public static TaiFengInfo jiexitaifengInfo(String str){

    TaiFengInfoDao tdao = new TaiFengInfoDao();
    JSONObject dataOfJson = JSONObject.fromObject(str);

// String begin_time = dataOfJson.getString("begin_time");
// String end_time = dataOfJson.getString("end_time");
String tfbh=dataOfJson.getString("tfbh");
String name=dataOfJson.getString("name");
String ename=dataOfJson.getString("ename");
int is_current=dataOfJson.getInt("is_current");
String land=dataOfJson.getString("land");
TaiFengInfo info=new TaiFengInfo();
info.setTfbh(tfbh);
// info.setBegin_time(begin_time);
info.setEname(ename);
info.setName(name);
// info.setEnd_time(end_time);
info.setIs_current(is_current);
info.setLand(land);
tdao.addtaifenglist(info);
return info;

}*/

/*private static String[] getStringArray4Json(String jsonString){  

    JSONArray jsonArray = JSONArray.fromObject(jsonString);  
    String[] stringArray = new String[jsonArray.size()];  
    for( int i = 0 ; i<jsonArray.size() ; i++ ){  
        stringArray[i] = jsonArray.getString(i);  

    }  

    return stringArray;  
}  
*/
/**
 * @param args
 */

public static   TaiFengInfo jiexitaifengInfo1(String str){
    TaiFengInfoDao tdao = new TaiFengInfoDao();

    String strj="{"+"results:"+str;
    JSONObject dataOfJson = JSONObject.fromObject(str);
     JSONArray results=dataOfJson.getJSONArray("results");  
     for(int i=0;i<results.size();i++){

         JSONObject Jinfo=results.getJSONObject(i);
         TaiFengInfo info=new TaiFengInfo();

     }  



    return null;

}
public static void main(String[] args) {  
    String url = "http://www.wztf121.com/data/complex/path.json?rand=7428111";  

// String url = "http://www.kuaidi100.com/query?type=yunda&postid=1201386764793";

String json = loadJson(url);

System.out.println(json);
String str="{"+json+"}";
System.out.println(str);
// jiexitaifengInfo(str);

    /* String[] stringArray=getStringArray4Json(json);
     System.out.println(stringArray[0]);*/

}  

}



7个回答

解析Json首先要搞明白的就是格式问题。所以我首先建议使用Chrome的一个拓展叫Json Handler。

简直是Json数据格式化的神器。然后你在按照Object后者Array的方式来解析,心情就会好很多了。

这里没贴代码,但是良心建议。

希望能帮到你 :-)

public static void main(String[] args) {

String string="[{'tfbh':'201611','name':'圆规','ename':'Kompasu','is_current':0,'begin_time':'2016-08-20T08:00:00','end_time':'2016-08-21T14:00:00','land':[]}," +
"{'tfbh':'201610','name':'狮子山','ename':'Lionrock','is_current':1,'begin_time':'2016-08-19T20:00:00','end_time':'2016-08-24T08:00:00','land':[]}," +
"{'tfbh':'201609','name':'蒲公英','ename':'Mindulle','is_current':0,'begin_time':'2016-08-19T14:00:00','end_time':'2016-08-23T02:00:00','land':[]}," +
"{'tfbh':'201608','name':'电母','ename':'Dianmu','is_current':0,'begin_time':'2016-08-18T05:00:00','end_time':'2016-08-19T23:00:00','land':[]}," +
"{'tfbh':'201607','name':'灿都','ename':'Chanthu','is_current':0,'begin_time':'2016-08-14T02:00:00','end_time':'2016-08-17T17:00:00','land':[]}," +
"{'tfbh':'201606','name':'康森','ename':'Conson','is_current':0,'begin_time':'2016-08-09T08:00:00','end_time':'2016-08-13T14:00:00','land':[]}," +
"{'tfbh':'201605','name':'奥麦斯','ename':'Omais','is_current':0,'begin_time':'2016-08-04T14:00:00','end_time':'2016-08-09T20:00:00','land':[]}," +
"{'tfbh':'201604','name':'妮妲','ename':'Nida','is_current':0,'begin_time':'2016-07-30T17:00:00','end_time':'2016-08-03T05:00:00','land':[]}," +
"{'tfbh':'201603','name':'银河','ename':'Mirinae','is_current':0,'begin_time':'2016-07-26T11:00:00','end_time':'2016-07-28T11:00:00','land':[]}," +
"{'tfbh':'201602','name':'卢碧','ename':'Lupit','is_current':0,'begin_time':'2016-07-24T02:00:00','end_time':'2016-07-25T02:00:00','land':[]}," +
"{'tfbh':'201601','name':'尼伯特','ename':'Nepartak','is_current':0,'begin_time':'2016-07-03T08:00:00','end_time':'2016-07-10T11:00:00','land':[]}]";

try {
JSONArray array = new JSONArray(string);
System.out.println(array.length());
for (int i = 0; i < array.length(); i++) {

JSONObject jsonObj = array.getJSONObject(i);
System.out.println(jsonObj.get("tfbh"));
System.out.println(jsonObj.get("name"));
System.out.println(jsonObj.get("ename"));
System.out.println(jsonObj.get("is_current"));
System.out.println(jsonObj.get("begin_time"));
System.out.println(jsonObj.get("end_time"));
System.out.println(jsonObj.get("land"));
//用一个实体类接收下,然后保存到数据库里
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


    JSONObject会报json要以"{"开头的错误

好乱:
json 数据格式,嵌套:


格式:[{"data":"_data"}]

例子如下:
{
  "statusCode": "200",
  "data": [
    {
        "havaTeam": "1"
    },

    {
        "user": {
              "id": 9615,
              "birthday": "",
              "username": "Curse.",
              "sex": "",
              "remark": "",
              "sourceuserid": "os0WpxFQZK2PPtDlpphEjzRE5c40",
              "firstlogtime": "",
              "usersource": "",
              "headimgurl": "http://wx.qlogo.cn/mmopen/iazJJcMFKX0hRFR6sWRwv50XKErFXsiaiaKWHTS19iaaeIdVMfibJJTXiaqtx7USmbVo8Qc9Gbwuu01jOOqvn76YWVyja3GclqQhm7/0",
              "islock": "0",
              "city": "黑龙江"
          }
     }
     ],

   "msg": ""
}


解析数据,从对应路径下通过 IO 流接收json 格式数据,解析,也可忽略这一步
直接看

“//获取服务器返回的 json 数据”

之后的内容,及对数据的处理

try {
            URL url = new URL("路径");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                InputStream is = conn.getInputStream();  //IO 流接收数据
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String json = br.readLine();
                datajson = new JSONObject(json);  //获取服务器返回的 json 数据

                //JSONObject obj1 = datajson.getJSONObject("statusCode");  //通过名获取对应对象
                //Stringobj1 = datajson.getString("result");  //直接获取数据
                JSONObject dataObj = datajson.getJSONObject("data");
                String _havaTeam = dataObj.getString("havaTeam");  
                int _statusCode = datajson.getInt("statusCode");  //获取 200

                JSONObject userObj = dataObj.getJSONObject("user");
                int _id = userObj.getInt("id");  // 9615
                String _username = userObj.getString("username");
//类似的都是这么写;基本对象为Obj 对象,一个json 数据可能包含多个obj 对象,
//对象数据也可嵌套存在。一对一数据对应,如:"statusCode": "200"

            } else {
                handler.sendEmptyMessage(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

首先你要懂json的格式。 然后通过观察json的规则,然后循环,存在一个对象里。 把对象存数据库里。 我只是一个打酱油路过的围观群众。

哥给你写个了完整的例子,如下:
/**

  • 公司名称:
  • 创建时间:2016年8月25日 上午11:19:05
  • 创建人 :Levi */ package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**

  • 类说明:
  • @author Levi
  • @since JDK 1.7
    */
    public class Main {

    public static void main(String args[]){

    String url = "http://www.kuaidi100.com/query?type=yunda&postid=1201386764793";
    String jsonStr = loadJson(url);
    System.out.println(jsonStr);
    
    Gson g = new Gson();
    Response response = g.fromJson(jsonStr, new TypeToken<Response>(){}.getType());
    System.out.println(response.getData().size());
    

    }

    private static String loadJson(String url) {
    StringBuffer sb = new StringBuffer();
    try {
    URL urlObject = new URL(url);

        URLConnection uc = urlObject.openConnection();
    
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
    
        String inputLine = null;
    
        while ((inputLine = in.readLine()) != null) {
            sb.append(inputLine);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sb.toString();
    

    }
    }

/**

  • 公司名称:
  • 创建时间:2016年8月25日 上午11:15:13
  • 创建人 :Levi */ package com.test;

import java.util.List;

/**

  • 类说明:
  • @author Levi
  • @since JDK 1.7
    */
    public class Response {

    private String message;
    private String nu;
    private String companytype;
    private String ischeck;
    private String com;
    private String updatetime;
    private String status;
    private String condition;
    private String codenumber;
    private String state;

    private List data;
    /**

    • @return the message / public String getMessage() { return message; } /*
    • @param message the message to set / public void setMessage(String message) { this.message = message; } /*
    • @return the nu / public String getNu() { return nu; } /*
    • @param nu the nu to set / public void setNu(String nu) { this.nu = nu; } /*
    • @return the companytype / public String getCompanytype() { return companytype; } /*
    • @param companytype the companytype to set / public void setCompanytype(String companytype) { this.companytype = companytype; } /*
    • @return the ischeck / public String getIscheck() { return ischeck; } /*
    • @param ischeck the ischeck to set / public void setIscheck(String ischeck) { this.ischeck = ischeck; } /*
    • @return the com / public String getCom() { return com; } /*
    • @param com the com to set / public void setCom(String com) { this.com = com; } /*
    • @return the updatetime / public String getUpdatetime() { return updatetime; } /*
    • @param updatetime the updatetime to set / public void setUpdatetime(String updatetime) { this.updatetime = updatetime; } /*
    • @return the status / public String getStatus() { return status; } /*
    • @param status the status to set / public void setStatus(String status) { this.status = status; } /*
    • @return the condition / public String getCondition() { return condition; } /*
    • @param condition the condition to set / public void setCondition(String condition) { this.condition = condition; } /*
    • @return the codenumber / public String getCodenumber() { return codenumber; } /*
    • @param codenumber the codenumber to set / public void setCodenumber(String codenumber) { this.codenumber = codenumber; } /*
    • @return the state / public String getState() { return state; } /*
    • @param state the state to set / public void setState(String state) { this.state = state; } /*
    • @return the data / public List getData() { return data; } /*
    • @param data the data to set */ public void setData(List data) { this.data = data; }

}

/**

  • 公司名称:
  • 创建时间:2016年8月25日 上午11:17:57
  • 创建人 :Levi */ package com.test;

/**

  • 类说明:
  • @author Levi
  • @since JDK 1.7
    */
    public class ReturnData {

    private String time;
    private String location;
    private String context;
    private String ftime;
    /**

    • @return the time / public String getTime() { return time; } /*
    • @param time the time to set / public void setTime(String time) { this.time = time; } /*
    • @return the location / public String getLocation() { return location; } /*
    • @param location the location to set / public void setLocation(String location) { this.location = location; } /*
    • @return the context / public String getContext() { return context; } /*
    • @param context the context to set / public void setContext(String context) { this.context = context; } /*
    • @return the ftime / public String getFtime() { return ftime; } /*
    • @param ftime the ftime to set */ public void setFtime(String ftime) { this.ftime = ftime; }

}

另附 gson包下载地址:https://github.com/google/gson/archive/master.zip

哥给你写个了完整的例子,如下:

 /**
 * 公司名称:
 * 创建时间:2016年8月25日 上午11:19:05
 * 创建人     :Levi
 */
package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 类说明:
 * @author Levi
 * @since JDK 1.7
 */
public class Main {

    public static void main(String args[]){

        String url = "http://www.kuaidi100.com/query?type=yunda&postid=1201386764793";
        String jsonStr = loadJson(url);
        System.out.println(jsonStr);


        Gson g = new Gson();
        Response response = g.fromJson(jsonStr, new TypeToken<Response>(){}.getType());
        System.out.println(response.getData().size());
    }

    private static String loadJson(String url) {
        StringBuffer sb = new StringBuffer();
        try {
            URL urlObject = new URL(url);

            URLConnection uc = urlObject.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

            String inputLine = null;

            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

/**
 * 公司名称:
 * 创建时间:2016年8月25日 上午11:15:13
 * 创建人     :Levi
 */
package com.test;

import java.util.List;

/**
 * 类说明:
 * @author Levi
 * @since JDK 1.7
 */
public class Response {

    private String message;
    private String nu;
    private String companytype;
    private String ischeck;
    private String com;
    private String updatetime;
    private String status;
    private String condition;
    private String codenumber;
    private String state;

    private List<ReturnData> data;
    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }
    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }
    /**
     * @return the nu
     */
    public String getNu() {
        return nu;
    }
    /**
     * @param nu the nu to set
     */
    public void setNu(String nu) {
        this.nu = nu;
    }
    /**
     * @return the companytype
     */
    public String getCompanytype() {
        return companytype;
    }
    /**
     * @param companytype the companytype to set
     */
    public void setCompanytype(String companytype) {
        this.companytype = companytype;
    }
    /**
     * @return the ischeck
     */
    public String getIscheck() {
        return ischeck;
    }
    /**
     * @param ischeck the ischeck to set
     */
    public void setIscheck(String ischeck) {
        this.ischeck = ischeck;
    }
    /**
     * @return the com
     */
    public String getCom() {
        return com;
    }
    /**
     * @param com the com to set
     */
    public void setCom(String com) {
        this.com = com;
    }
    /**
     * @return the updatetime
     */
    public String getUpdatetime() {
        return updatetime;
    }
    /**
     * @param updatetime the updatetime to set
     */
    public void setUpdatetime(String updatetime) {
        this.updatetime = updatetime;
    }
    /**
     * @return the status
     */
    public String getStatus() {
        return status;
    }
    /**
     * @param status the status to set
     */
    public void setStatus(String status) {
        this.status = status;
    }
    /**
     * @return the condition
     */
    public String getCondition() {
        return condition;
    }
    /**
     * @param condition the condition to set
     */
    public void setCondition(String condition) {
        this.condition = condition;
    }
    /**
     * @return the codenumber
     */
    public String getCodenumber() {
        return codenumber;
    }
    /**
     * @param codenumber the codenumber to set
     */
    public void setCodenumber(String codenumber) {
        this.codenumber = codenumber;
    }
    /**
     * @return the state
     */
    public String getState() {
        return state;
    }
    /**
     * @param state the state to set
     */
    public void setState(String state) {
        this.state = state;
    }
    /**
     * @return the data
     */
    public List<ReturnData> getData() {
        return data;
    }
    /**
     * @param data the data to set
     */
    public void setData(List<ReturnData> data) {
        this.data = data;
    }


}


/**
 * 公司名称:
 * 创建时间:2016年8月25日 上午11:17:57
 * 创建人     :Levi
 */
package com.test;

/**
 * 类说明:
 * @author Levi
 * @since JDK 1.7
 */
public class ReturnData {

    private String time;
    private String location;
    private String context;
    private String ftime;
    /**
     * @return the time
     */
    public String getTime() {
        return time;
    }
    /**
     * @param time the time to set
     */
    public void setTime(String time) {
        this.time = time;
    }
    /**
     * @return the location
     */
    public String getLocation() {
        return location;
    }
    /**
     * @param location the location to set
     */
    public void setLocation(String location) {
        this.location = location;
    }
    /**
     * @return the context
     */
    public String getContext() {
        return context;
    }
    /**
     * @param context the context to set
     */
    public void setContext(String context) {
        this.context = context;
    }
    /**
     * @return the ftime
     */
    public String getFtime() {
        return ftime;
    }
    /**
     * @param ftime the ftime to set
     */
    public void setFtime(String ftime) {
        this.ftime = ftime;
    }

}



另附 gson包下载地址:https://github.com/google/gson/archive/master.zip

json解析,建议你用 alibaba.fastjson 这个jar包,里面有很详尽的方法。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问