引入是要的maven依赖:
1 <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
2 <dependency>
3 <groupId>com.google.code.gson</groupId>
4 <artifactId>gson</artifactId>
5 <version>2.2.4</version>
6 </dependency>
转换:
1 package com.iot.zjdy.exampl.test;
2
3 import com.google.gson.JsonArray;
4 import com.google.gson.JsonElement;
5 import com.google.gson.JsonObject;
6 import com.google.gson.JsonParser;
7 import java.io.BufferedWriter;
8 import java.io.File;
9 import java.io.FileReader;
10 import java.io.FileWriter;
11
12
13 /**
14 * Created by Yanwu 2018/2/8.
15 */
16 public class JsonToSqlTest {
17 private static final String PATH = "C:\\demo\\file\\Cab_LN_FeaturesToJSON.json";
18
19 public static void main(String[] args) throws Exception {
20 System.out.println("========== JSON ---> 转换成 SQL 开始 ==========");
21 jsonToExcel();
22 System.out.println("========== JSON ---> 转换成 SQL 结束 ==========");
23 }
24
25 private static void jsonToExcel() throws Exception {
26 JsonParser jsonParser = new JsonParser();
27 JsonObject jsonObject = (JsonObject) jsonParser.parse(new FileReader(PATH));
28 JsonElement features = jsonObject.get("features");
29 JsonArray asJsonArray = features.getAsJsonArray();
30 for (int i = 0; i < asJsonArray.size(); i++) {
31 JsonElement jsonElement = asJsonArray.get(i);
32 JsonObject featuresObj = jsonElement.getAsJsonObject();
33 JsonElement attributes = featuresObj.get("attributes");
34 JsonObject attributesObj = attributes.getAsJsonObject();
35 JsonElement swchName = attributesObj.get("swchName");
36 String nameStr = swchName.toString();
37 JsonElement geometry = featuresObj.get("geometry");
38 JsonObject geometryObj = geometry.getAsJsonObject();
39 JsonElement path = geometryObj.get("paths");
40 String pathStr = path.toString();
41 String replace = nameStr.replace("\"", "");
42 String sqlStr = "insert into poly_line (id, box_name, paths) values (" + i + ", '" + replace + "', '" + pathStr + "'); \r\n";
43 System.out.println(sqlStr);
44 File file = new File("C:\\demo\\file\\Cab_LN.sql");
45 if (!file.exists()) {
46 file.createNewFile();
47 }
48 FileWriter fileWriter = new FileWriter(file, true);
49 BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
50 bufferedWriter.write(sqlStr);
51 bufferedWriter.close();
52 }
53 }
54 }