List of usage examples for com.google.gson JsonElement toString
@Override
public String toString()
From source file:jetbrick.web.mvc.results.GsonResultHandler.java
License:Open Source License
@Override public void handle(RequestContext ctx, JsonElement result) throws IOException { HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); if (result == null) { JsonObject json = new JsonObject(); Enumeration<String> e = request.getAttributeNames(); while (e.hasMoreElements()) { String name = e.nextElement(); Object value = request.getAttribute(name); json.add(name, gson.toJsonTree(value)); }// w ww . j a v a 2 s. c o m for (Map.Entry<String, Object> entry : ctx.getModel().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); json.add(key, gson.toJsonTree(value)); } result = json; } String characterEncoding = request.getCharacterEncoding(); response.setCharacterEncoding(characterEncoding); String mimetype = MimetypeUtils.getJSON(request); response.setContentType(mimetype + "; charset=" + characterEncoding); PrintWriter out = response.getWriter(); out.write(result.toString()); out.flush(); }
From source file:JSONformating.reader.JSONReader.java
public static JValue getJValue(JsonObject cell) throws IOException { JSONFormatType type = JSONFormatType.getType(cell.get("type").getAsString()); JsonElement value = cell.get("value"); switch (type) { case BOOLEAN: JBooleanValue boolValue = new JBooleanValue(); boolValue.setValue(value.getAsBoolean()); return boolValue; case DATE:// ww w.j a va2 s. c om case IMAGE: case STRING: case URL: case VERSION: JStringValue stringValue = new JStringValue(); stringValue.setValue(value.getAsString()); return stringValue; case INTEGER: case REAL: JNumberValue numValue = new JNumberValue(); numValue.setValue(value.getAsDouble()); return numValue; case MULTIPLE: JMultipleValue mulValue = new JMultipleValue(); JsonArray array = value.getAsJsonArray(); for (JsonElement j : array) { if (j instanceof JsonNull) { System.out.println("JsonNull in JSONReader.getJValue(...)"); System.out.println(value.toString()); } else { mulValue.addValue(getJValueForMultiple(j)); } } return mulValue; case UNDEFINED: default: return null; } }
From source file:jwatson.util.CustomEvidenceDeserializer.java
License:Apache License
@Override public Evidencelist deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { if (jsonElement.toString().equals("{}")) { return null; }// w w w. j av a 2s. c om JsonObject jsonObject = jsonElement.getAsJsonObject(); Gson gson = new Gson(); Evidencelist evidence = gson.fromJson(jsonObject, Evidencelist.class); return evidence; }
From source file:microsoft.aspnet.signalr.client.tests.util.Utils.java
License:Open Source License
public static void addResultHandlersToConnection(Connection connection, final MultiResult result, final boolean throwOnError) { connection.connected(new Runnable() { @Override//from w ww.ja v a2 s . com public void run() { result.statesResult.add(ConnectionState.Connected); } }); connection.closed(new Runnable() { @Override public void run() { result.statesResult.add(ConnectionState.Disconnected); } }); connection.reconnected(new Runnable() { @Override public void run() { result.statesResult.add(ConnectionState.Connected); } }); connection.reconnecting(new Runnable() { @Override public void run() { result.statesResult.add(ConnectionState.Reconnecting); } }); connection.received(new MessageReceivedHandler() { @Override public void onMessageReceived(JsonElement json) { result.listResult.add(json.toString()); } }); connection.error(new ErrorCallback() { @Override public void onError(Throwable error) { result.errorsResult.add(error); if (throwOnError) { throw new RuntimeException(error); } } }); }
From source file:myhomehelper.Listen.java
@Override public void run() { while (true)/*from w ww . ja v a2 s. c o m*/ if (!isSet) { try { Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection("jdbc:mysql://localhost/user_login", "root", ""); statement = (Statement) connect.createStatement(); size = statement.executeQuery("select count(channel) from Status"); size.first(); //System.out.println(""+size.getInt(1)); channels = new String[size.getInt(1)]; size.close(); resultSet = statement.executeQuery("select channel from Status"); while (resultSet.next()) { //System.out.println(""+resultSet.getString(1)); channels[i++] = resultSet.getString(1); } //for(String a : channels) // System.out.println(""+a); pubnub.addListener(new SubscribeCallback() { @Override public void status(PubNub pubnub, PNStatus pns) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void message(PubNub pubnub, PNMessageResult pnmr) { try { String c = pnmr.getChannel(); JsonElement msg = pnmr.getMessage(); System.out.println("" + msg); String T = msg.toString(); if (T.contains("!")) { String t = T.substring(1, T.indexOf('!')); temp = Integer.parseInt(t); System.out.println("Temp " + temp); T = T.substring(T.indexOf('!') + 1); t = T.substring(0, T.indexOf('!')); int S = Integer.parseInt(t); if (S > 512) Plant = true; else Plant = false; System.out.println("Soil " + t); T = T.substring(T.indexOf('!') + 1); t = T.substring(0, T.indexOf('!')); int R = Integer.parseInt(t); if (R > 512) // TODO Rain = true; else Rain = false; System.out.println("Rain " + t); //From here // create a mysql database connection String myDriver = "com.mysql.jdbc.Driver"; String myUrl = "jdbc:mysql://localhost/user_login"; Class.forName(myDriver); Connection conn = DriverManager.getConnection(myUrl, "root", ""); // the mysql insert statement String query = " update Status set temp = ? where channel='0'"; // create the mysql insert preparedstatement PreparedStatement preparedStmt = (PreparedStatement) conn .prepareStatement(query); preparedStmt.setInt(1, temp); // execute the preparedstatement preparedStmt.execute(); conn.close(); } } catch (Exception e) { System.out.println("" + e.getMessage()); } //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void presence(PubNub pubnub, PNPresenceEventResult pnper) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); pubnub.subscribe().channels(Arrays.asList("0")).execute(); //System.out.println("asddddddddddddd"); } catch (Exception e) { System.out.println("Error " + e.toString()); } isSet = true; } else { pubnub.publish().channel("0").message("asdasdd"); } //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }
From source file:net.doubledoordev.backend.util.TypeHellhole.java
License:Open Source License
public static void set(Field field, Object object, JsonElement value) throws Exception { if (field.getType() == byte.class) field.setByte(object, value.getAsByte()); else if (field.getType() == short.class) field.setShort(object, value.getAsShort()); else if (field.getType() == int.class) field.setInt(object, value.getAsInt()); else if (field.getType() == long.class) field.setLong(object, value.getAsLong()); else if (field.getType() == float.class) field.setFloat(object, value.getAsFloat()); else if (field.getType() == double.class) field.setDouble(object, value.getAsDouble()); else if (field.getType() == boolean.class) field.setBoolean(object, value.getAsBoolean()); else if (field.getType() == char.class) field.setChar(object, value.getAsCharacter()); ////from w ww .j a v a2 s.c om else if (field.getType() == Byte.class) field.set(object, value.getAsByte()); else if (field.getType() == Short.class) field.set(object, value.getAsShort()); else if (field.getType() == Integer.class) field.set(object, value.getAsInt()); else if (field.getType() == Long.class) field.set(object, value.getAsLong()); else if (field.getType() == Float.class) field.set(object, value.getAsFloat()); else if (field.getType() == Double.class) field.set(object, value.getAsDouble()); else if (field.getType() == Boolean.class) field.set(object, value.getAsBoolean()); else if (field.getType() == Character.class) field.set(object, value.getAsCharacter()); // else if (field.getType() == String.class) field.set(object, value.getAsString()); else { String m = String.format("Unknown type! Field type: %s Json value: %s Data class: %s", field.getType(), value.toString(), object.getClass().getSimpleName()); Main.LOGGER.error(m); throw new Exception(m); } }
From source file:net.nexustools.njs.JSON.java
License:Open Source License
public JSON(final Global global) { super(global); setHidden("stringify", new AbstractFunction(global) { public java.lang.String stringify(BaseObject object) { StringBuilder builder = new StringBuilder(); stringify(object, builder);/*from ww w . ja v a 2s . c om*/ return builder.toString(); } public void stringify(BaseObject object, StringBuilder builder) { if (Utilities.isUndefined(object)) { builder.append("null"); return; } BaseObject toJSON = object.get("toJSON", OR_NULL); if (toJSON != null) stringify0(((BaseFunction) toJSON).call(object), builder); else stringify0(object, builder); } public void stringify0(BaseObject object, StringBuilder builder) { if (object instanceof GenericArray) { builder.append('['); if (((GenericArray) object).length() > 0) { stringify(object.get(0), builder); for (int i = 1; i < ((GenericArray) object).length(); i++) { builder.append(','); stringify(object.get(i), builder); } } builder.append(']'); } else if (object instanceof String.Instance) { builder.append('"'); builder.append(object.toString()); builder.append('"'); } else if (object instanceof Number.Instance) { double number = ((Number.Instance) object).value; if (Double.isNaN(number) || Double.isInfinite(number)) builder.append("null"); builder.append(object.toString()); } else if (object instanceof Boolean.Instance) builder.append(object.toString()); else { builder.append('{'); Iterator<java.lang.String> it = object.keys().iterator(); if (it.hasNext()) { java.lang.String key = it.next(); builder.append('"'); builder.append(key); builder.append("\":"); stringify(object.get(key), builder); if (it.hasNext()) { do { builder.append(','); key = it.next(); builder.append('"'); builder.append(key); builder.append("\":"); stringify(object.get(key), builder); } while (it.hasNext()); } } builder.append('}'); } } @Override public BaseObject call(BaseObject _this, BaseObject... params) { switch (params.length) { case 0: return Undefined.INSTANCE; case 1: if (params[0] == Undefined.INSTANCE) return Undefined.INSTANCE; return global.wrap(stringify(params[0])); default: return global.wrap("undefined"); } } @Override public java.lang.String name() { return "JSON_stringify"; } }); setHidden("parse", new AbstractFunction(global) { final Gson GSON; { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(BaseObject.class, new JsonDeserializer<BaseObject>() { @Override public BaseObject deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { if (je.isJsonNull()) return Null.INSTANCE; if (je.isJsonPrimitive()) { JsonPrimitive primitive = je.getAsJsonPrimitive(); if (primitive.isBoolean()) return primitive.getAsBoolean() ? global.Boolean.TRUE : global.Boolean.FALSE; if (primitive.isNumber()) return global.wrap(primitive.getAsDouble()); if (primitive.isString()) return global.wrap(primitive.getAsString()); throw new UnsupportedOperationException(primitive.toString()); } if (je.isJsonObject()) { GenericObject go = new GenericObject(global); JsonObject jo = je.getAsJsonObject(); for (Map.Entry<java.lang.String, JsonElement> entry : jo.entrySet()) { go.set(entry.getKey(), deserialize(entry.getValue(), type, jdc)); } return go; } if (je.isJsonArray()) { JsonArray ja = je.getAsJsonArray(); BaseObject[] array = new BaseObject[ja.size()]; for (int i = 0; i < array.length; i++) { array[i] = deserialize(ja.get(i), type, jdc); } return new GenericArray(global, array); } throw new UnsupportedOperationException(je.toString()); } }); GSON = gsonBuilder.create(); } @Override public BaseObject call(BaseObject _this, BaseObject... params) { try { return GSON.fromJson(params[0].toString(), BaseObject.class); } catch (com.google.gson.JsonSyntaxException ex) { throw new Error.JavaException("SyntaxError", "Unexpected token", ex); } } @Override public java.lang.String name() { return "JSON_parse"; } }); }
From source file:net.osten.watermap.convert.PCTReport.java
License:Open Source License
private Set<WaterReport> parseDocument(JsonObject reportJson) { Set<WaterReport> results = new HashSet<WaterReport>(); log.info("json children=" + reportJson.getAsJsonArray("values").size()); JsonArray currentRow = null;//w ww . j a v a 2 s . c om for (JsonElement row : reportJson.getAsJsonArray("values")) { if (row.isJsonArray()) { currentRow = row.getAsJsonArray(); log.info("row has " + currentRow.size() + "elements"); if (currentRow.size() >= 6) { try { String waypoint = currentRow.get(2).getAsJsonPrimitive().getAsString(); String desc = currentRow.get(3).getAsJsonPrimitive().getAsString(); String rpt = currentRow.get(4).getAsJsonPrimitive().getAsString(); String date = currentRow.get(5).getAsJsonPrimitive().getAsString(); log.info("waypoint=" + waypoint); String[] names = waypoint.split(","); for (String name : names) { name = name.trim(); WaterReport report = processWaypoint(name, desc, date, rpt); if (report.getLat() == null) { // DEO try prefixing the name (this is for split names: "WR127,B") name = names[0] + name; report = processWaypoint(name, desc, date, rpt); if (report.getLat() == null) { log.info("cannot find coords for " + waypoint); } else { log.info("Adding " + report.toString()); results.add(report); } } else { log.info("Adding " + report.toString()); results.add(report); } } } catch (Exception e) { e.printStackTrace(); } } else { log.info("skipping row " + row.toString()); } } else { log.warning("row is not json array but " + row.getClass().getName()); } } log.info("returning " + results.size() + " pct reports"); return results; }
From source file:net.patrickpollet.gson.JsonBooleanDeserializer.java
License:Open Source License
public Boolean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try {/*from www. ja v a2 s . c o m*/ String value = json.getAsJsonPrimitive().getAsString(); return value.toLowerCase().equals("true"); } catch (ClassCastException e) { throw new JsonParseException("Cannot parse json boolean '" + json.toString() + "'", e); } }
From source file:net.uiqui.couchdb.protocol.impl.QueryResult.java
License:Apache License
public List<String> resultAsListOfString() { final List<String> output = new ArrayList<>(); for (final JsonElement jsonElement : results) { output.add(jsonElement.toString()); }//from www .jav a2s. c o m return output; }