Groovy 读取json文件,并用gson反序列化
package com.bicycle.utilimport bicycle_grails.StationInfoimport com.google.gson.Gsonimport com.google.gson.JsonArrayimport com.google.gson.JsonObjectimport com.google.gson.JsonParserimport com.google.gson.reflect.TypeTokenimport 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 retList = gson.fromJson(jsonArray, new TypeToken >(){}.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 }}