2011-07-20 13 views
8

Czy ktoś może mi pomóc, jak utworzyć obiekt JSON z bazy danych?Obiekt Json z bazy danych w java

To właśnie JSON wyjście powinna wyglądać następująco:

{“devicelist”:{ 
    “device”: [ 
    {“id”: “01”, “type”: “CAM”, “name”: “Livingroom”} 
    {“id”: “15”, “type”: “CAM”, “name”: “Kitchen”} 
] 
}} 

To mój kod:

if (reg!=null) 
{ 

    try 
        { 
        con = ds.getConnection(); 
        Statement select = con.createStatement(); 
        ResultSet result=select.executeQuery("Select type,name,demo from register_device"); 
         while (result.next()) 
         { 
         String type_json=result.getString("type"); 
         String name_json=result.getString("name"); 
         String id_json=result.getString("demo"); 
         JSONArray arrayObj=new JSONArray(); 

         } 
        } 
        catch(Exception e) 
        { 

        } 
     } 

jestem w stanie dostać wybrany typ, nazwa, demo z bazy danych.

Nie wiem, jak rozpocząć kodowanie JSON.

+0

które tabele bazy danych kolumna (wymienione powyżej) przechowuje wartości json? –

+0

Witam, mam takie same wymagania i będę bardzo wdzięczny, jeśli możesz mi powiedzieć, czy istnieje prosty i elegancki sposób konwertowania SQL na JSON przy użyciu standardowej biblioteki Java (Java.net. *) Lub czegokolwiek, co nie jest słoikami stron trzecich . Również "JSONARRAY" ... to trzecia strona? Będę bardzo wdzięczny, jeśli ktoś może mi odpowiedzieć: – user3384231

Odpowiedz

8

Jeśli chcesz, aby wyodrębnić dane z DB i skonstruować JSON Object siebie, można zrobić:

JsonArray jArray = new JsonArray(); 
while (result.next()) 
{ 
    String type_json=result.getString("type"); 
    String name_json=result.getString("name"); 
    String id_json=result.getString("demo"); 
    JsonObject jObj = new JsonObject(); 
    jobj.put("id", id_json); 
    jobj.put("type", type_json); 
    jobj.put("name", name_json); 
    jArray.put(jObj); 
} 

JsonObject jObjDevice = new JsonObject(); 
jObjDevice.put("device", jArray); 
JsonObject jObjDeviceList = new JsonObject(); 
jObjDevice.put("devicelist", jObjDevice); 

teraz jObjDeviceList zawiera wszystkie dane.

0

Z jOOQ, można wytworzyć podobną listę JSON z bazy danych:

String json = create.select(TYPE, NAME, DEMO) 
        .from(REGISTER_DEVICE) 
        .fetch() 
        .formatJSON(); 

JSON String będzie wyglądać następująco:

{fields:["TYPE","NAME","DEMO"], 
records:[["01","CAM","Livingroom"],["15","CAM","Kitchen"]]} 

To nie jest dokładnie to, co wymagane w pytaniu, ale może nie zależy Ci na formacie, który zasugerowałeś JSON? Ponadto, możesz być w stanie przekształcić ten obiekt JSON później.

Zobacz więcej tutaj:

http://sourceforge.net/apps/trac/jooq/wiki/Manual/ADVANCED/Export

0

Jeśli masz obiekty Device, json-lib może serializować obiekt przy użyciu metod get() jako JSON.

import java.util.*; 
import net.sf.json.*; 

public class JsonEncode { 
    public static void main(String[] args) throws Exception { 
     Device d1 = new Device("01", "CAM", "LivingRoom"); 
     Device d2 = new Device("15", "CAM", "Kitchen"); 

     List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2)); 

     JSONArray serializedDevices = JSONArray.fromObject(devices); 
     JSONObject jsonDevices = new JSONObject(); 
     jsonDevices.put("devices", serializedDevices); 

     JSONObject json = new JSONObject(); 
     json.put("deviceList", jsonDevices); 
     System.out.println(json); 
    } 

    public static class Device { 
     Device(String id, String type, String name) { 
      this.id = id; 
      this.type = type; 
      this.name = name; 
     } 
     private String id; 
     public String getId() { return id; } 
     private String type; 
     public String getType() { return type; } 
     private String name; 
     public String getName() { return name; } 
    } 
} 

zapisany jako: JsonEncode.java

skompilowany z:

javac -cp json-lib-2.4-jdk15.jar JsonEncode.java 

Wykonane z (uwaga: ścieżka klasy DOS separatora):

java -cp .;json-lib-2.4-jdk15.jar;commons-lang-2.6.jar;commons-logging-1.1.1.jar;commons-collections-3.2.1.jar;ezmorph-1.0.6.jar;commons-beanutils-1.8.0.jar JsonEncode 

zależności:

0
package com.idal.cib; 

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.SQLException; 

public class DatabaseConnector { 

    static Connection conn1 = null; 

    public static Connection getDbConnection(String driver, String url, 
      String username, String password) { 
     // TODO Auto-generated constructor stub 
     try { 

      Class.forName(driver); 

      conn1 = DriverManager.getConnection(url, username, password); 
     } catch (ClassNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return conn1; 
    } 

} 


package com.idal.cib; 

import java.io.FileWriter; 
import java.io.IOException; 
import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.ResultSetMetaData; 
import java.sql.SQLException; 
import java.util.ArrayList; 

import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 

public class DBJsonConverter { 

    static ArrayList<String> data = new ArrayList<String>(); 
    static Connection conn = null; 
    static PreparedStatement ps = null; 
    static ResultSet rs = null; 
    static String path = ""; 
    static String driver=""; 
    static String url=""; 
    static String username=""; 
    static String password=""; 
    static String query=""; 

    @SuppressWarnings({ "unchecked" }) 
    public static void dataLoad(String path) { 
     JSONObject obj1 = new JSONObject(); 
     JSONArray jsonArray = new JSONArray(); 
     conn = DatabaseConnector.getDbConnection(driver, url, username, 
       password); 
     try { 
      ps = conn.prepareStatement(query); 
      rs = ps.executeQuery(); 
      ArrayList<String> columnNames = new ArrayList<String>(); 
      if (rs != null) { 
       ResultSetMetaData columns = rs.getMetaData(); 
       int i = 0; 
       while (i < columns.getColumnCount()) { 
        i++; 
        columnNames.add(columns.getColumnName(i)); 
       } 
       while (rs.next()) { 
        JSONObject obj = new JSONObject(); 
        for (i = 0; i < columnNames.size(); i++) { 
         data.add(rs.getString(columnNames.get(i))); 
         { 
          for (int j = 0; j < data.size(); j++) { 
           if (data.get(j) != null) { 
            obj.put(columnNames.get(i), data.get(j)); 
           }else { 
            obj.put(columnNames.get(i), ""); 
           } 
          } 
         } 
        } 

        jsonArray.add(obj); 
        obj1.put("header", jsonArray); 
        FileWriter file = new FileWriter(path); 
        file.write(obj1.toJSONString()); 
        file.flush(); 
        file.close(); 
       } 
       ps.close(); 
      } else { 
       JSONObject obj2 = new JSONObject(); 
       obj2.put(null, null); 
       jsonArray.add(obj2); 
       obj1.put("header", jsonArray); 
      } 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } finally { 
      if (conn != null) { 
       try { 
        conn.close(); 
        rs.close(); 
        ps.close(); 
       } catch (SQLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 

    @SuppressWarnings("static-access") 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     driver = "oracle.jdbc.driver.OracleDriver"; 
     url = "jdbc:oracle:thin:@10.11.34.134:1521:COREMUAT"; 
     username = "oasisusr"; 
     password = "p#g_ay0w"; 
     path = "D:\\VF_Polaris\\968670\\category_list1.json"; 
     query = "select * from temp_employee"; 

     DatabaseConnector dc = new DatabaseConnector(); 
     dc.getDbConnection(driver,url,username,password); 
     DBJsonConverter formatter = new DBJsonConverter(); 
     formatter.dataLoad(path); 

    } 

} 
+0

Pl dodaj wyjaśnienie do twojej odpowiedzi. –

Powiązane problemy