Java实现将json数据转换为sql insert语句

Java?p>

迪纸玧son数据转换为sql insert语句

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Iterator;
import java.util.Map;

public class JsonToSqlInsert {

    public static void main(String[] args) throws JsonProcessingException {

        String tableName = "";
        String json = "";
        System.out.println(parseSQL(tableName, json));

    }

    public static String parseSQL(String tableName, String json) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        
        JsonNode rootNode = objectMapper.readTree(json);

        String table_name = "INSERT INTO " + tableName + " (";

        StringBuilder sqlBuilder = new StringBuilder(table_name);

        for (Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields(); iterator.hasNext();) {
            Map.Entry<String, JsonNode> entry = iterator.next();

            if (!iterator.hasNext()) {
                sqlBuilder.append(entry.getKey());
            } else {
                sqlBuilder.append(entry.getKey()).append(", ");
            }

        }

        sqlBuilder.append(") VALUES ('");

        for (Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields(); iterator.hasNext();) {
            Map.Entry<String, JsonNode> entry = iterator.next();

            String str = entry.getValue().toString();
            str = str.substring(1, str.length() - 1);

            if (!iterator.hasNext()) {
                sqlBuilder.append(str);
            } else {
                sqlBuilder.append(str).append("', '");
            }

        }

        sqlBuilder.append("');");

        return sqlBuilder.toString();

    }

}