2015-07-01 75 views
1

您好我有Java類,它將讀取&從文件解析JSON數據並插入到數據庫中,它們存儲NAME,AGE和PHONE。該程序工作正常,但我的要求是,我有需要做同樣的操作,我想存儲AGEIDTYPE。我在過去的部分提到我的JSON數據不同的JSON數據解析來自文本文件的JSON數據

我從https://javapages4all.wordpress.com/2012/12/10/read-from-json-file-and-persist-into-mysql/

test.json驗證碼:

{'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類:

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 < 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<Object> iterator = nameArray.iterator(); 

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

     for (int i = 0; i < size; i++) { 
      if (i < (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<Object> 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; 
    } 
} 

我的JSON:

[{"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"}] 

對於上面的程序我想用這個JSON數據

+2

不,解析你會得到對象後 - 那麼你可能要重新格式化,以這種格式...雖然目前還不清楚爲什麼你在第二個例子中沒有使用JSON。 (JSON字符串*總是*使用雙引號,就我在規範中可以看到的那樣)。 –

+0

其實我正在尋找邏輯來獲取只有年齡,ID和類型 – Rakesh

+2

正確,所以這就是所有你應該問的 - 你的問題沒有'現在不說了。接下來,向我們展示您已經嘗試過的方法 - 在Web上解析JSON時有大量資源,因此您不應該在開始時遇到問題。請顯示一個簡短但完整的程序,顯示您到目前爲止的內容,並指出問題所在。 –

回答

1

試試這個

import org.codehaus.jettison.json.JSONArray; 
import org.codehaus.jettison.json.JSONException; 
import org.codehaus.jettison.json.JSONObject; 

public class GetDataFromJSON { 
public static void main(String[] args) { 
    String json = "[{\"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\"}]"; 
    JSONArray jsonArray = getDesiredJSONArray(json); 
    System.out.println(jsonArray); 
} 

public static JSONArray getDesiredJSONArray(String json) { 
    JSONArray jsonArray = null; 
    JSONArray desiredJsonArray = new JSONArray(); 
    try { 
     jsonArray = new JSONArray(json); 
     for (int i = 0; i < jsonArray.length(); i++) { 
      // System.out.println(jsonArray.get(i)); 
      JSONObject object = new JSONObject(jsonArray.get(i).toString()); 
      JSONObject jsonObject = new JSONObject(); 
      jsonObject.put("type", object.get("type")); 
      object = new JSONObject(object.get("emp").toString()); 
      jsonObject.put("ID", object.get("ID")); 
      jsonObject.put("age", object.get("age")); 
      desiredJsonArray.put(jsonObject); 
     } 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return desiredJsonArray; 
} 
} 
+0

這是完整的答案:)(y) –

+0

謝謝Soheil Setayeshi –

+0

請檢查上面編輯的代碼 – Rakesh

1

要做到這一點,你必須首先收杆,並保存在某個地方的值,然後創建所需的JSON對象格式並通過第一階段的解析值設置其值。 例如在安卓/ Java的:

ArrayList<YourDataNode> arrayList = new ArrayList<>(); 
    for (int i=0 ; i<jsonArray.length() ; i++) { 
     JSONObject jsonObject = jsonArray.get(i); 
     JSONObject empObject = jsonObject.getJSONObject("emp"); 
     String type = jsonObject.getString("type"); 
     int age = empObject.getInt("age"); 
     long id = empObject.getLong("id"); 
     YourDataNode temp = new (id, age, type); 
     arrayList.add(temp); 
    } 
2

我爲使用Gson解析json的情況下一個簡單的例子。

public class Result { 
    private long id; 
    private int age; 
    private String type; 

    public Result(long id, int age, String type) { 
     this.age = age; 
     this.id = id; 
     this.type = type; 
    } 
} 

public class EmployeeInfo { 
    private int age; 
    @SerializedName("ID") 
    private long id; 

    public EmployeeInfo(int age, long id) { 
     this.age = age; 
     this.id = id; 
    } 
} 

public class Employee { 
    @SerializedName("emp") 
    private EmployeeInfo employeeInfo; 
    private String type; 

    public Employee(EmployeeInfo employeeInfo, String type) { 
     this.employeeInfo = employeeInfo; 
     this.type = type; 
    } 
} 

運行:

public static void main(String[] args) throws IOException { 
    String json = "[{\"emp\":{\"age\":34,\"ID\":3423423},\"type\":\"s\"}, \n" + 
      "{\"emp\":{\"age\":43,\"ID\":324324235},\"type\":\"s\"}, \n" + 
      "{\"emp\":{\"age\":36,\"ID\":324324236},\"type\":\"v\"},\n" + 
      "{\"emp\":{\"age\":46,\"ID\":324324238},\"type\":\"s\"},\n" + 
      "{\"emp\":{\"age\":55,\"ID\":324324243},\"type\":\"s\"},\n" + 
      "{\"emp\":{\"age\":44,\"ID\":324324287},\"type\":\"s\"}]"; 

    Gson gson = new Gson(); 
    Type type = new TypeToken<List<Employee>>() { 
    }.getType(); 
    List<Employee> employees = gson.fromJson(json, type); 
    List<Result> results = new ArrayList<>(); 

    Result result; 
    for (Employee employee : employees) { 
     result = new Result(employee.getEmployeeInfo().getId(), employee.getEmployeeInfo().getAge(), employee.getType()); 

     results.add(result); 
    } 

    System.out.println(gson.toJson(results)); 

}