0
如何從JSONObject中將動態鍵值插入到數據庫中。解析JSONObject並將動態鍵/值插入到數據庫中
我能夠從發佈請求中提取關鍵值並單獨輸出,但我無法管理它將它們存儲在數據庫中。
@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;
}
JSON對象經由客戶端發送帶有角:
{
"formData":
[
{
"id":235,
"username":"john",
"enabled":"true",
"last_login":"2017-03-03 19:49:56",
"pass":"xxxxx"
}
]
}
數據庫是Postgres的9.6.1
錯誤(堆棧跟蹤):
org.postgresql.util.PSQLException: ERROR: column "xxxxx" does not exist
Position: 34
我有一個邏輯while循環中的錯誤,但我無法弄清楚。