List of usage examples for com.google.gson.stream JsonReader JsonReader
public JsonReader(Reader in)
From source file:abtlibrary.utils.as24ApiClient.JSON.java
License:Apache License
/** * Deserialize the given JSON string to Java object. * * @param <T> Type/* w w w.ja v a 2 s .c o m*/ * @param body The JSON string * @param returnType The type to deserialize inot * @return The deserialized Java object */ @SuppressWarnings("unchecked") public <T> T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { JsonReader jsonReader = new JsonReader(new StringReader(body)); // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) jsonReader.setLenient(true); return gson.fromJson(jsonReader, returnType); } else { return gson.fromJson(body, returnType); } } catch (JsonParseException e) { // Fallback processing when failed to parse JSON form response body: // return the response body string directly for the String return type; // parse response body into date or datetime for the Date return type. if (returnType.equals(String.class)) return (T) body; else if (returnType.equals(Date.class)) return (T) apiClient.parseDateOrDatetime(body); else throw (e); } }
From source file:at.univie.sensorium.preferences.Preferences.java
License:Open Source License
private void loadPrefsFromStream(InputStream input) { List<BasicNameValuePair> preferencelist = new LinkedList<BasicNameValuePair>(); try {/*from ww w.j av a 2 s .c o m*/ InputStreamReader isreader = new InputStreamReader(input); JsonReader reader = new JsonReader(isreader); // String jsonVersion = ""; reader.beginArray(); // do we have an array or just a single object? reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); String value = reader.nextString(); if (name.equalsIgnoreCase(PREFERENCES_VERSION)) currentPrefVersion = Integer.valueOf(value); BasicNameValuePair kv = new BasicNameValuePair(name, value); preferencelist.add(kv); } reader.endObject(); reader.endArray(); reader.close(); if (newerPrefsAvailable()) { Log.d(SensorRegistry.TAG, "Newer preferences available in json, overwriting existing."); for (BasicNameValuePair kv : preferencelist) { putPreference(kv.getName(), kv.getValue()); } // also reset the welcome screen putBoolean(WELCOME_SCREEN_SHOWN, false); } else { Log.d(SensorRegistry.TAG, "Preferences are recent, not overwriting."); } } catch (FileNotFoundException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } catch (IOException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } }
From source file:au.com.addstar.cellblock.utilities.Utilities.java
License:Open Source License
public static <T extends Serializable> T loadFile(File file, TypeToken<T> type) { if (!file.exists()) { return null; }/*from ww w. ja va 2 s . c o m*/ try { InputStream in = new FileInputStream(file); InputStreamReader inread = new InputStreamReader(in); JsonReader reader = new JsonReader(inread); return gsonEncoder.fromJson(reader, type.getType()); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; }
From source file:au.edu.unsw.cse.soc.federatedcloud.deployers.github.repository.GitHubClient.java
License:Open Source License
/** * Parse JSON to specified type/*from ww w .j a v a 2s. c o m*/ * * @param <V> * @param stream * @param type * @param listType * @return parsed type * @throws IOException */ protected <V> V parseJson(InputStream stream, Type type, Type listType) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, CHARSET_UTF8), bufferSize); if (listType == null) try { return gson.fromJson(reader, type); } catch (JsonParseException jpe) { IOException ioe = new IOException("Parse exception converting JSON to object"); //$NON-NLS-1$ ioe.initCause(jpe); throw ioe; } finally { try { reader.close(); } catch (IOException ignored) { // Ignored } } else { JsonReader jsonReader = new JsonReader(reader); try { if (jsonReader.peek() == BEGIN_ARRAY) return gson.fromJson(jsonReader, listType); else return gson.fromJson(jsonReader, type); } catch (JsonParseException jpe) { IOException ioe = new IOException("Parse exception converting JSON to object"); //$NON-NLS-1$ ioe.initCause(jpe); throw ioe; } finally { try { jsonReader.close(); } catch (IOException ignored) { // Ignored } } } }
From source file:au.edu.unsw.cse.soc.federatedcloud.deployers.github.repository.GitHubRepoDeploymentWrapper.java
License:Open Source License
protected <V> V parseJson(InputStream stream, Type type, Type listType) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, CHARSET_UTF8), bufferSize); if (listType == null) try {//from ww w .ja va2s . c om return gson.fromJson(reader, type); } catch (JsonParseException jpe) { IOException ioe = new IOException("Parse exception converting JSON to object"); //$NON-NLS-1$ ioe.initCause(jpe); throw ioe; } finally { try { reader.close(); } catch (IOException ignored) { // Ignored } } else { JsonReader jsonReader = new JsonReader(reader); try { if (jsonReader.peek() == BEGIN_ARRAY) return gson.fromJson(jsonReader, listType); else return gson.fromJson(jsonReader, type); } catch (JsonParseException jpe) { IOException ioe = new IOException("Parse exception converting JSON to object"); //$NON-NLS-1$ ioe.initCause(jpe); throw ioe; } finally { try { jsonReader.close(); } catch (IOException ignored) { // Ignored } } } }
From source file:Batch.TweetReader.java
@Override public void open(Serializable checkpoint) throws Exception { BufferedReader in = new BufferedReader( new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("kwetterinput.json"))); reader = new JsonReader(in); reader.beginObject();// ww w . ja v a 2 s . co m reader.nextName(); reader.beginArray(); gson = new Gson(); }
From source file:be.iminds.iot.dianne.dataset.DatasetConfigurator.java
License:Open Source License
private void parseDatasetConfiguration(File f) { try {//from w w w . java 2s. c o m // parse any adapter configurations from JSON and apply config? JsonParser parser = new JsonParser(); JsonObject json = parser.parse(new JsonReader(new FileReader(f))).getAsJsonObject(); String name = json.get("name").getAsString(); if (name == null) return; // should have a name Hashtable<String, Object> props = new Hashtable<>(); String dir = f.getParentFile().getAbsolutePath(); props.put("dir", dir); String pid = null; if (json.has("adapter")) { String adapter = json.get("adapter").getAsString(); pid = adapter.contains(".") ? adapter : "be.iminds.iot.dianne.dataset.adapters." + adapter; // in case of adapter, set Dataset target: the dataset it is adapting String dataset = json.get("dataset").getAsString(); props.put("Dataset.target", "(name=" + dataset + ")"); } else if (json.has("type")) { String type = json.get("type").getAsString(); pid = "be.iminds.iot.dianne.dataset." + type; } else { // some hard coded pids if (name.startsWith("MNIST")) { pid = "be.iminds.iot.dianne.dataset.MNIST"; } else if (name.startsWith("CIFAR-100")) { pid = "be.iminds.iot.dianne.dataset.CIFAR100"; } else if (name.startsWith("CIFAR-10")) { pid = "be.iminds.iot.dianne.dataset.CIFAR10"; } else if (name.startsWith("STL-10")) { pid = "be.iminds.iot.dianne.dataset.STL10"; } else if (name.startsWith("SVHN")) { pid = "be.iminds.iot.dianne.dataset.SVHN"; } else if (name.equalsIgnoreCase("ImageNetValidation")) { pid = "be.iminds.iot.dianne.dataset.ImageNet.validation"; } else if (name.equalsIgnoreCase("ImageNetTraining")) { pid = "be.iminds.iot.dianne.dataset.ImageNet.training"; } else { pid = "be.iminds.iot.dianne.dataset." + name; } } // set an aiolos instance id using the dataset name to treat // equally named datasets as single instance in the network props.put("aiolos.instance.id", name); // combine all offered interfaces (might be SequenceDataset or ExperiencePool) props.put("aiolos.combine", "*"); // TODO use object conversion from JSON here? Configuration config = ca.createFactoryConfiguration(pid, null); json.entrySet().stream().forEach(e -> { if (e.getValue().isJsonArray()) { JsonArray a = e.getValue().getAsJsonArray(); String[] val = new String[a.size()]; for (int i = 0; i < val.length; i++) { val[i] = a.get(i).getAsString(); } props.put(e.getKey(), val); } else { props.put(e.getKey(), e.getValue().getAsString()); } }); config.update(props); } catch (Exception e) { System.err.println("Error parsing Dataset config file: " + f.getAbsolutePath()); e.printStackTrace(); } }
From source file:be.iminds.iot.dianne.jsonrpc.DianneJSONRPCCLI.java
License:Open Source License
public void jsonrpc(String requestString) { JsonWriter writer = new JsonWriter(new PrintWriter(System.out)); try {//from w w w .j a v a 2s. com if (requestString.contains("://")) { // treat as URI URI uri = new URI(requestString); JsonReader reader = new JsonReader(new InputStreamReader(uri.toURL().openStream())); handler.handleRequest(reader, writer); } else { // treat as json request string JsonObject request = parser.parse(requestString).getAsJsonObject(); handler.handleRequest(request, writer); } } catch (Exception e) { e.printStackTrace(); } }
From source file:be.iminds.iot.dianne.jsonrpc.DianneJSONRPCServlet.java
License:Open Source License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json"); try (JsonReader reader = new JsonReader(req.getReader()); JsonWriter writer = new JsonWriter(resp.getWriter())) { handler.handleRequest(reader, writer); } catch (Exception e) { e.printStackTrace();/*w ww .j a v a 2 s . c o m*/ } }
From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java
License:Open Source License
public static NeuralNetworkDTO parseJSON(InputStream i) { JsonReader reader = new JsonReader(new InputStreamReader(i)); JsonObject json = parser.parse(reader).getAsJsonObject(); return parseJSON(json); }