Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.opencarte.db; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.opencarte.model.DataSet; import com.opencarte.model.Geometry; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.io.IOUtils; /** * * @author Michal */ public class Parser { protected String fileContent = null; protected GsonBuilder builder; protected Gson gson; public Parser() { } public Parser(String fileName) { try { this.fileContent = IOUtils.toString(new URL(fileName).openStream()); builder = new GsonBuilder(); } catch (IOException ex) { System.out.println(ex); //Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex); } } public DataSet[] getDataSet() { DataSet[] dataSet = null; JsonDeserializer<DataSet> datasetDes = new JsonDeserializer<DataSet>() { @Override public DataSet deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { JsonObject deserialize = je.getAsJsonObject(); Geometry geo = new Geometry(deserialize.get("geometry").getAsJsonObject().get("type").getAsString(), deserialize.get("geometry").getAsJsonObject().get("coordinates").getAsJsonArray().get(1) .getAsDouble(), deserialize.get("geometry").getAsJsonObject().get("coordinates").getAsJsonArray().get(0) .getAsDouble()); return new DataSet(deserialize.get("datasetid").getAsString(), deserialize.get("recordid").getAsString(), geo); } }; builder.registerTypeAdapter(DataSet.class, datasetDes); gson = builder.create(); try { dataSet = gson.fromJson(fileContent, DataSet[].class); } catch (JsonParseException ex) { System.out.println("Invalid JSON: " + ex.getMessage()); } return dataSet; } }