List of usage examples for com.google.gson JsonElement getAsJsonObject
public JsonObject getAsJsonObject()
From source file:ca.ualberta.cmput301w14t08.geochan.json.ThreadCommentJsonConverter.java
License:Apache License
/** * Deserializes a ThreadComment object from JSON format. * /*from www.j a v a 2 s.c o m*/ * @param json the JsonElement * @param type the Type * @param context the JsonDeserializationContext * * @return The deserialized ThreadComment. * * @throws JsonParseException */ @Override public ThreadComment deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject object = json.getAsJsonObject(); String title = object.get("title").getAsString(); long threadDate = object.get("threadDate").getAsLong(); boolean hasImage = object.get("hasImage").getAsBoolean(); String locationString = object.get("location").getAsString(); List<String> locationEntries = Arrays.asList(locationString.split(",")); double latitude = Double.parseDouble(locationEntries.get(0)); double longitude = Double.parseDouble(locationEntries.get(1)); String user = object.get("user").getAsString(); String hash = object.get("hash").getAsString(); String id = object.get("id").getAsString(); String textPost = object.get("textPost").getAsString(); String locationDescription = null; if (object.get("locationDescription") != null) { locationDescription = object.get("locationDescription").getAsString(); } Bitmap thumbnail = null; if (hasImage) { /* * http://stackoverflow.com/questions/20594833/convert-byte-array-or- * bitmap-to-picture */ // http://stackoverflow.com/a/5878773 // Sando's workaround for running out of memory on decoding bitmaps. BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inDither = false; // Disable Dithering mode opts.inPurgeable = true; // Tell to gc that whether it needs free // memory, the Bitmap can be cleared opts.inInputShareable = true; // Which kind of reference will be // used to recover the Bitmap data // after being clear, when it will be // used in the future opts.inTempStorage = new byte[32 * 1024]; String encodedThumb = object.get("imageThumbnail").getAsString(); byte[] thumbArray = Base64.decode(encodedThumb, Base64.NO_WRAP); thumbnail = BitmapFactory.decodeByteArray(thumbArray, 0, thumbArray.length, opts); } GeoLocation location = new GeoLocation(latitude, longitude); location.setLocationDescription(locationDescription); final Comment c = new Comment(textPost, null, location, null); c.getCommentDate().setTime(threadDate); c.setUser(user); c.setHash(hash); c.setId(Long.parseLong(id)); if (hasImage) { c.setImageThumb(thumbnail); } final ThreadComment comment = new ThreadComment(c, title); comment.setThreadDate(new Date(threadDate)); comment.setId(Long.parseLong(id)); return comment; }
From source file:ca.ualberta.cmput301w14t08.geochan.json.ThreadCommentOfflineJsonConverter.java
License:Apache License
/** * Deserializes a ThreadComment object from JSON format. * /*from w w w . j av a 2s. com*/ * @param json The JsonElement to deserialize. * @param type The Type. * @param context The JsonDeserializationContext. * * @return The deserialized ThreadComment. */ @Override public ThreadComment deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject object = json.getAsJsonObject(); String title = object.get("title").getAsString(); long threadDate = object.get("threadDate").getAsLong(); boolean hasImage = object.get("hasImage").getAsBoolean(); String locationString = object.get("location").getAsString(); List<String> locationEntries = Arrays.asList(locationString.split(",")); double latitude = Double.parseDouble(locationEntries.get(0)); double longitude = Double.parseDouble(locationEntries.get(1)); String user = object.get("user").getAsString(); String hash = object.get("hash").getAsString(); String id = object.get("id").getAsString(); String textPost = object.get("textPost").getAsString(); String locationDescription = null; if (object.get("locationDescription") != null) { locationDescription = object.get("locationDescription").getAsString(); } ArrayList<Comment> topList = new ArrayList<Comment>(); recursiveDeserialize(object, id, topList); Bitmap thumbnail = null; if (hasImage) { /* * http://stackoverflow.com/questions/20594833/convert-byte-array-or- * bitmap-to-picture */ String encodedThumb = object.get("imageThumbnail").getAsString(); byte[] thumbArray = Base64.decode(encodedThumb, Base64.NO_WRAP); thumbnail = BitmapFactory.decodeByteArray(thumbArray, 0, thumbArray.length); } GeoLocation location = new GeoLocation(latitude, longitude); location.setLocationDescription(locationDescription); final Comment c = new Comment(textPost, null, location, null); c.getCommentDate().setTime(threadDate); c.setUser(user); c.setHash(hash); c.setId(Long.parseLong(id)); c.setChildren(topList); if (hasImage) { c.setImageThumb(thumbnail); } final ThreadComment comment = new ThreadComment(c, title); comment.setThreadDate(new Date(threadDate)); comment.setId(Long.parseLong(id)); return comment; }
From source file:ca.ualberta.CMPUT301W15T06.GsonAdapter.java
License:Apache License
@Override public T deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { // TODO Auto-generated method stub JsonObject jsonObject = json.getAsJsonObject(); JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME); String className = prim.getAsString(); Class<?> klass = null;// w w w . ja v a 2 s . co m try { klass = Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new JsonParseException(e.getMessage()); } return context.deserialize(jsonObject.get(INSTANCE), klass); }
From source file:ca.ualberta.cs.scandaloutraveltracker.mappers.UserMapper.java
License:Apache License
@Override public Location deserialize(JsonElement element, Type arg1, JsonDeserializationContext jdc) throws JsonParseException { JsonObject jo = element.getAsJsonObject(); Location location = new Location(jo.getAsJsonPrimitive("provider").getAsString()); location.setAccuracy(jo.getAsJsonPrimitive("accuracy").getAsFloat()); location.setLatitude(jo.getAsJsonPrimitive("latitude").getAsDouble()); location.setLongitude(jo.getAsJsonPrimitive("longitude").getAsDouble()); return location; }
From source file:ca.ualberta.cs.team1travelexpenseapp.gsonUtils.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }/*w w w .j a v a 2 s. c om*/ final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }; }
From source file:ca.uhn.fhir.jpa.util.jsonpatch.CopyOperation.java
License:Apache License
@Override public JsonElement apply(JsonElement original) { JsonElement result = duplicate(original); JsonElement item = path.head().navigate(result); JsonElement data = mySourcePath.head().navigate(original); if (item.isJsonObject()) { item.getAsJsonObject().add(path.tail(), data); } else if (item.isJsonArray()) { JsonArray array = item.getAsJsonArray(); int index = (path.tail().equals("-")) ? array.size() : Integer.valueOf(path.tail()); List<JsonElement> temp = new ArrayList<JsonElement>(); Iterator<JsonElement> iter = array.iterator(); while (iter.hasNext()) { JsonElement stuff = iter.next(); iter.remove();//from w w w. j a v a 2 s . co m temp.add(stuff); } temp.add(index, data); for (JsonElement stuff : temp) { array.add(stuff); } } return result; }
From source file:cc.kave.commons.utils.json.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }// w ww . j a v a 2 s .com final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); // (kave adaptation) was: ".remove(typeFiledName)" JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that // subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { if (value == null) { Streams.write(null, out); return; } Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that // subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); // (kave adaptation) disabled check // if (jsonObject.has(typeFieldName)) { // throw new JsonParseException("cannot serialize " + // srcType.getName() // + " because it already defines a field named " + // typeFieldName); // } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }; }
From source file:ccm.pay2spawn.configurator.Configurator.java
License:Open Source License
private void setupModels() { mainTable.setModel(new AbstractTableModel() { @Override//from w w w.ja v a 2 s . c om public int getRowCount() { return rootArray.size(); } @Override public int getColumnCount() { return COLUMN_NAMES.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { JsonObject jsonObject = rootArray.get(rowIndex).getAsJsonObject(); if (!jsonObject.has(COLUMN_KEYS[columnIndex])) return ""; switch (columnIndex) { default: return jsonObject.get(COLUMN_KEYS[columnIndex]).getAsString(); case 4: HashSet<String> types = new HashSet<>(); for (JsonElement element : jsonObject.getAsJsonArray(COLUMN_KEYS[columnIndex])) types.add(element.getAsJsonObject().get("type").getAsString()); return JOINER_COMMA_SPACE.join(types); } } @Override public String getColumnName(int column) { return COLUMN_NAMES[column]; } }); typeList.setModel(new AbstractListModel<String>() { final ArrayList<String> names = TypeRegistry.getNames(); @Override public int getSize() { return names.size(); } @Override public String getElementAt(int index) { return names.get(index); } }); rewards.setModel(new AbstractListModel<String>() { @Override public int getSize() { return rewardData == null ? 0 : rewardData.size(); } @Override public String getElementAt(int index) { if (rewardData.get(index).getAsJsonObject().has("type")) return rewardData.get(index).getAsJsonObject().getAsJsonPrimitive("type").getAsString(); else return "ERROR IN CONFIG - No type for reward " + index; } }); }
From source file:ccm.pay2spawn.permissions.PermissionsDB.java
License:Open Source License
public void load() throws IOException { File file = getFile();//from w w w .j a va 2s. com if (file.exists()) { JsonObject rootObject = JSON_PARSER.parse(new FileReader(file)).getAsJsonObject(); for (JsonElement element : rootObject.getAsJsonArray("players")) { Player player = new Player(element.getAsJsonObject()); playerDB.put(player.getName(), player); } for (JsonElement element : rootObject.getAsJsonArray("groups")) { Group group = new Group(element.getAsJsonObject()); groupDB.put(group.getName(), group); } } else { //noinspection ResultOfMethodCallIgnored file.createNewFile(); JsonObject rootObject = new JsonObject(); rootObject.add("players", new JsonArray()); rootObject.add("groups", new JsonArray()); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(GSON.toJson(rootObject)); bw.close(); } }
From source file:ccm.pay2spawn.util.Helper.java
License:Open Source License
/** * Fill in variables from a donation/* ww w. j a v a 2s . c om*/ * * @param dataToFormat data to be formatted * @param donation the donation data * * @return the fully var-replaced JsonElement */ public static JsonElement formatText(JsonElement dataToFormat, Donation donation, Reward reward) { if (dataToFormat.isJsonPrimitive() && dataToFormat.getAsJsonPrimitive().isString()) { return new JsonPrimitive(Helper.formatText(dataToFormat.getAsString(), donation, reward)); } if (dataToFormat.isJsonArray()) { JsonArray out = new JsonArray(); for (JsonElement element : dataToFormat.getAsJsonArray()) { out.add(formatText(element, donation, reward)); } return out; } if (dataToFormat.isJsonObject()) { JsonObject out = new JsonObject(); for (Map.Entry<String, JsonElement> entity : dataToFormat.getAsJsonObject().entrySet()) { out.add(entity.getKey(), Helper.formatText(entity.getValue(), donation, reward)); } return out; } return dataToFormat; }