Java实现将json数据转换为sql insert语句
Java实现将json数据转换为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();
}
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_41924879/article/details/135679024