Parsing JSON data from text file

admin

Administrator
Staff member
Hi I have Java class which will read &amp;parse the JSON data from file and insert into DB,they are storing NAME,AGE and PHONE. The program is working fine;But my requirement is ,I have a different JSON data which needs to do same operation,I want to store <strong>AGE</strong>,<strong>ID</strong> and <strong>TYPE</strong>.I have mentioned my JSON data in the last part

I got this code from the <a href="https://javapages4all.wordpress.com/2012/12/10/read-from-json-file-and-persist-into-mysql/" rel="nofollow">https://javapages4all.wordpress.com/2012/12/10/read-from-json-file-and-persist-into-mysql/</a>

test.json:

Code:
{'profiles':[
{'name':'Girish', 'age': 44, 'phone':'203-203-2030'},
{'name':'Alex','age':31, 'phone':'203-203-2030'},
{'name':'Amy', 'age': 24, 'phone':'203-203-2030'},
{'name':'Melissa','age':21, 'phone':'203-203-2030'}
]
}

Java Class:

Code:
package com.sample.json;


import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;

public class MyJson {
    private static String tableName = "jsontest";

    public static void main(String[] args) {
        try {
            ClassLoader cl = MyJson.class.getClassLoader();
            InputStream is = cl.getResourceAsStream("test.json");
            String str = IOUtils.toString(is);
            JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str);
            System.out.println(jsonObject);
            JSONArray jsonArr = jsonObject.getJSONArray("profiles");
            JSONObject obj = null;
            JSONArray nameArr = null;
            JSONArray valArr = null;

            for (int i = 0; i &lt; jsonArr.size(); i++) {
                obj = jsonArr.getJSONObject(i);
                nameArr = obj.names();
                valArr = obj.toJSONArray(nameArr);
                //saveRecord(nameArr, valArr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void saveRecord(JSONArray nameArray, JSONArray valArray) {
        Connection conn = getConnection();
        StringBuffer sb = new StringBuffer("insert into " + tableName + "(");
        int size = nameArray.size();
        int count = 0;
        Iterator&lt;Object&gt; iterator = nameArray.iterator();

        while (iterator.hasNext()) {
            if (count &lt; (size - 1))
                sb.append(iterator.next() + ",");
            else
                sb.append(iterator.next() + ")");
            count++;
        }
        sb.append(" values(");

        for (int i = 0; i &lt; size; i++) {
            if (i &lt; (size - 1))
                sb.append("?,");
            else
                sb.append("?)");
        }
        System.out.println(sb.toString());
        try {
            PreparedStatement pstmt = conn.prepareStatement(sb.toString());
            bindVariables(valArray, pstmt);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void bindVariables(JSONArray valArray,
            PreparedStatement pstmt) throws SQLException {
        Iterator&lt;Object&gt; iterator = valArray.iterator();
        int cnt = 0;
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            if (obj instanceof String) {
                pstmt.setString(++cnt, (String) obj);
            } else if (obj instanceof Integer) {
                pstmt.setLong(++cnt, (Integer) obj);
            } else if (obj instanceof Long) {
                pstmt.setLong(++cnt, (Long) obj);
            } else if (obj instanceof Double) {
                pstmt.setDouble(++cnt, (Double) obj);
            }
        }
    }

    private static Connection getConnection() {
        Connection con = null;
        String url = "jdbc:mysql://localhost:3306/";
        String db = "jsondata";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pass = "root";
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, user, pass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
}

My JSON:

Code:
[{"emp":{"age":34,"ID":3423423},"type":"s"}, 
{"emp":{"age":43,"ID":324324235},"type":"s"}, 
{"emp":{"age":36,"ID":324324236},"type":"v"},
{"emp":{"age":46,"ID":324324238},"type":"s"},
{"emp":{"age":55,"ID":324324243},"type":"s"},
{"emp":{"age":44,"ID":324324287},"type":"s"}]

for the above program i want to use this JSON data