我有一個包含產品信息的JSON文檔,我想解析JSON文檔並將其放入數據庫。Java - 如何將JSON文檔解析爲數據庫
一個例子JSON文件:
{
"itemize": {
"pr": "2583",
"n": "Chocolate donut",
"yst": "A beautiful, premium chocolate donut"
"wh": 2.99
}
這裏是我到目前爲止的代碼:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class q1 {
public static void addProduct()
{
JSONParser parser=new JSONParser();
try{
Object obj = parser.parse(new FileReader("c.\\itemize.json"));
JSONObject jsonObject = (JSONObject) obj;
String pr = (String) jsonObject.get("Pr");
//Put pr into database
String n = (String) jsonObject.get("n");
//Put n into database
String yst = (String) jsonObject.get("yst");
//Put yst into database
String wh = (String) jsonObject.get("wh");
//Put wh into database
}
}
}
數據庫是MySQL和擁有所有這些列了。我只需要用將把字符串放入數據庫的行來替換java代碼中的註釋行。這是數據庫的樣子:
Pr VARCHAR(30) NOT NULL,
n VARCHAR(30) NOT NULL,
yst VARCHAR(30) NOT NULL,
wh VARCHAR(30) NOT NULL,
Primary Key (Product_ID));
使用'java.sql.PreparedStatement'。 –
爲了使代碼有用,您確實需要添加第二條記錄,所以某些代碼會讓所有標籤都有所不同,以供您理解,並可能會改變您的編碼方式。 –