解析JSONObject并将动态键/值插入数据库

时间:2017-03-03 19:39:00

标签: java json postgresql jersey-2.0

如何将JSONObject中的动态键值插入数据库。

我可以从Post Request中提取键值并单独输出,但我无法管理它以将它们存储在数据库中。

@POST
@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String keyValueFromJson(String userFormData) throws JSONException {

    PreparedStatement query = null;
    Connection conn = null;

    JSONObject jsOb = new JSONObject(userFormData);
    JSONArray jaArr = jsOb.getJSONArray("formData");

    try {

        conn = DaoMessenger.PostGresCon().getConnection();

        for (int i = 0; i < jaArr.length();) {
            JSONObject jsonObject = jaArr.getJSONObject(i);
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                Object value = jsonObject.get(key);
                System.out.println( key + ": " + value );
                query = conn.prepareStatement ( "INSERT INTO users (" + key + ") values( " + value + ")" );
                ResultSet rs = query.executeQuery();
            }

            i++;
        }

    } catch (Exception e){
        e.printStackTrace();
    }

    return userFormData;
}

使用Angular通过客户端发送JSON对象:

{
"formData":
[
    {
        "id":235,
        "username":"john",
        "enabled":"true",
        "last_login":"2017-03-03 19:49:56",
        "pass":"xxxxx"

    }
]
}

数据库是Postgres 9.6.1

错误(StackTrace):

org.postgresql.util.PSQLException: ERROR: column "xxxxx" does not exist
Position: 34

我在while循环中有一个逻辑错误,但我无法弄明白。

1 个答案:

答案 0 :(得分:0)

我做了一些改动,它的工作原理如下:

StringBuilder sbv = new StringBuilder();
StringBuilder sbk = new StringBuilder();
String prefix = "";

    try {
        conn = DaoMessenger.PostGresCon().getConnection(); 
        for (int i = 0; i < jaArr.length();) {
            JSONObject jsonObject = jaArr.getJSONObject(i);
            Iterator<String> keys = jsonObject.keys();

            while (keys.hasNext()) {
                String key = keys.next();
                Object value = jsonObject.get(key);
                sbk.append(prefix);
                sbv.append(prefix);
                prefix = ",";
                sbv.append("'").append(value).append("'");
                sbk.append(key);
            }
            query = conn.prepareStatement("INSERT INTO users (" + sbk.toString() + ") values (" + sbv.toString() + ")" );
            ResultSet rs = query.executeQuery();

            i++;
        }

    } catch (Exception e){
        e.printStackTrace();
    }