Groovy 讀取json文件,並用gson反序列化
package com.bicycle.util
import bicycle_grails.StationInfo
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import java.io.*
/**
* Created by gao on 2017/3/22.
*/
class Test {
static void main(String[] args) {
String data = ReadFile("C:\\project\\station.json");
SqlConnect.init()
//創建gson對象,用於json處理
Gson gson=new Gson()
//將從json字符串中讀取的數據轉換為接送對象
JsonObject returnData = new JsonParser().parse(data).getAsJsonObject()
//獲取json數組對象
JsonArray jsonArray= returnData.getAsJsonArray("station")
//將json數組對象轉換成list集合,gson提供fromJson方法進行放序列化
List<StationInfo> retList = gson.fromJson(jsonArray, new TypeToken<List<StationInfo>>(){}.getType())
for(StationInfo stationInfo:retList){
def sql="insert into station_info (station_id, area_id,station_name,lng,lat,lng1,lat1,stall_num,address,is_all_day,person_duty) values (${stationInfo.station_id}, ${stationInfo.area_id},${stationInfo.station_name},${stationInfo.lng},${stationInfo.lat},${stationInfo.lng1},${stationInfo.lat1},${stationInfo.stall_num},${stationInfo.address},${stationInfo.is_all_day},${stationInfo.person_duty})"
println(sql)
SqlConnect.getConnection().execute(sql)
}
}
static String ReadFile(String Path) {
BufferedReader reader = null
String laststr = ""
try {
//將json文件讀入fileInputStream對象
FileInputStream fileInputStream = new FileInputStream(Path)
//將文件流轉換為字符輸入流,格式為UTF-8
//InputStreamReader : 是字節流與字符流之間的橋梁,能將字節流輸出為字符流,並且能為字節流指定字符集,可輸出一個個的字符;
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8")
//BufferedReader : 提供通用的緩沖方式文本讀取,readLine讀取一個文本行,也可以從字符輸入流中讀取文本,緩沖各個字符,從而提供字符、數組和行的高效讀取。
reader = new BufferedReader(inputStreamReader)
String tempString = null
while ((tempString = reader.readLine()) != null) {
laststr += tempString
}
reader.close()
} catch (IOException e) {
e.printStackTrace()
} finally {
if (reader != null) {
try {
reader.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
return laststr
}
}