List of usage examples for com.google.gson JsonParseException JsonParseException
public JsonParseException(Throwable cause)
From source file:de.symeda.sormas.app.rest.RuntimeTypeAdapterFactory.java
License:Open Source 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. 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); JsonElement labelJsonElement; if (maintainType) { labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); } else { 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 (maintainType) { Streams.write(jsonObject, out); return; } JsonObject clone = new JsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }.nullSafe(); }
From source file:donky.microsoft.aspnet.signalr.client.DateSerializer.java
License:Open Source License
/** * Deserializes a JsonElement containing an ISO-8601 formatted date *///from ww w. jav a 2 s .c om @Override public Date deserialize(JsonElement element, Type type, JsonDeserializationContext ctx) throws JsonParseException { String strVal = element.getAsString(); try { return deserialize(strVal); } catch (ParseException e) { throw new JsonParseException(e); } }
From source file:donky.microsoft.aspnet.signalr.client.DateSerializer.java
License:Open Source License
/** * Deserializes an ISO-8601 formatted date *///from www . jav a 2 s .c o m public static Date deserialize(String strVal) throws ParseException { String s; if (strVal.contains("+00:00")) { strVal = strVal.replace("+00:00", ""); } if (strVal.length() == 19) {// adapt from format yyyy-MM-ddTHH:mm:dd s = strVal + ".+00:00"; } else if (strVal.contains(".Z")) { // Change .Z to +00:00 to adapt the string to a format // that can be parsed in Java s = strVal.replace(".Z", ".+00:00"); } else { // Change Z to +00:00 to adapt the string to a format // that can be parsed in Java s = strVal.replace("Z", ".+00:00"); } try { // Remove the ":" character to adapt the string to a // format // that can be parsed in Java if (s.length() > THREE_MILLISECONDS_DATE_FORMAT_LENGTH) { // yyyy-MM-ddTHH:mm:dd.SSS+00:00 // remove the extra milliseconds characters s = s.substring(0, 23) + s.substring(s.length() - 6); } else if (s.length() < THREE_MILLISECONDS_DATE_FORMAT_LENGTH) { // add extra milliseconds characters int dif = (THREE_MILLISECONDS_DATE_FORMAT_LENGTH - s.length()); String zeros = ""; for (int i = 0; i < dif; i++) { zeros += "0"; } s = s.substring(0, 20 + (3 - dif)) + zeros + s.substring(s.length() - 6); } s = s.substring(0, 26) + s.substring(27); } catch (IndexOutOfBoundsException e) { throw new JsonParseException("Invalid length for: " + s); } // Parse the well-formatted date string SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSSZ"); dateFormat.setTimeZone(TimeZone.getDefault()); Date date = dateFormat.parse(s); return date; }
From source file:edu.wpi.cs.wpisuitetng.modules.AbstractEntityManager.java
License:Open Source License
/** * This static utility method takes a JSON string and attempts to * retrieve a username field from it. * @param serializedUser a JSON string containing a password * @return the username field parsed./*from w w w .ja va2 s. c o m*/ */ public static String parseFieldFromJSON(String serializedModel, String FieldName) { if (!serializedModel.contains(FieldName)) { throw new JsonParseException("The given JSON string did not contain specified field."); } int fieldStartIndex = serializedModel.indexOf(FieldName); int separator = serializedModel.indexOf(':', fieldStartIndex); int startIndex = serializedModel.indexOf('"', separator) + 1; int endIndex = serializedModel.indexOf('"', startIndex); String field = serializedModel.substring(startIndex, endIndex); return field; }
From source file:edu.wpi.cs.wpisuitetng.modules.core.entitymanagers.UserManager.java
License:Open Source License
/** * This static utility method takes a JSON string and attempts to * retrieve a username field from it. * @param serializedUser a JSON string containing a password * @return the username field parsed./*from w w w . j a v a 2 s . co m*/ */ public static String parseUsername(String serializedUser) { logger.log(Level.FINE, "Attempting username parsing..."); if (serializedUser == null || !serializedUser.contains("username")) { throw new JsonParseException("The given JSON string did not contain a username field."); } int fieldStartIndex = serializedUser.indexOf("username"); int separator = serializedUser.indexOf(':', fieldStartIndex); int startIndex = serializedUser.indexOf('"', separator) + 1; int endIndex = serializedUser.indexOf('"', startIndex); String username = serializedUser.substring(startIndex, endIndex); logger.log(Level.FINE, "Username parsing success!"); return username; }
From source file:edu.wpi.cs.wpisuitetng.modules.core.models.ProjectDeserializer.java
License:Open Source License
@Override public Project deserialize(JsonElement projectElement, Type projectType, JsonDeserializationContext context) throws JsonParseException { JsonObject deflated = projectElement.getAsJsonObject(); // check for the unique identifier <idNum> field. if (!deflated.has("idNum")) { throw new JsonParseException("The serialized Project did not contain the required idNum field."); }/*from ww w. j ava 2s . co m*/ // for all other attributes: instantiate as null, fill in if given. //int idNum = deflated.get("idNum").getAsInt(); String idNum = deflated.get("idNum").getAsString(); String name = null; User owner = null; String ownerString = null; User[] team = null; String[] supportedModules = null; if (deflated.has("name")) { name = deflated.get("name").getAsString(); } if (deflated.has("owner")) { owner = User.fromJSON(deflated.get("owner").getAsString()); } if (deflated.has("supportedModules")) { ArrayList<String> tempList = new ArrayList<String>(); JsonArray tempMods = deflated.get("supportedModules").getAsJsonArray(); for (JsonElement mod : tempMods) { tempList.add(mod.getAsString()); } String[] tempSM = new String[1]; supportedModules = tempList.toArray(tempSM); } Project inflated = new Project(name, idNum, owner, team, supportedModules); if (deflated.has("team")) { JsonArray tempTeam = deflated.get("team").getAsJsonArray(); for (JsonElement member : tempTeam) { inflated.addTeamMember(User.fromJSON(member.getAsString())); } } return inflated; }
From source file:edu.wpi.cs.wpisuitetng.modules.core.models.UserDeserializer.java
License:Open Source License
@Override public User deserialize(JsonElement userElement, Type userType, JsonDeserializationContext context) throws JsonParseException { JsonObject deflated = userElement.getAsJsonObject(); if (!deflated.has("username")) { throw new JsonParseException("The serialized User did not contain the required username field."); }/*ww w . j a v a 2 s . c o m*/ // for all other attributes: instantiate as null, fill in if given. int idNum = 0; String username = deflated.get("username").getAsString(); String name = null; String password = null; if (deflated.has("idNum") && !deflated.get("idNum").getAsString().equals("")) { try { idNum = deflated.get("idNum").getAsInt(); } catch (java.lang.NumberFormatException e) { logger.log(Level.FINER, "User transmitted with String in iDnum field"); } } if (deflated.has("password") && !deflated.get("password").getAsString().equals("")) { password = deflated.get("password").getAsString(); } if (deflated.has("name") && !deflated.get("name").getAsString().equals("")) { name = deflated.get("name").getAsString(); } User inflated = new User(name, username, password, idNum); if (deflated.has("role") && !deflated.get("role").getAsString().equals("")) { Role r = Role.valueOf(deflated.get("role").getAsString()); inflated.setRole(r); } return inflated; }
From source file:edu.wpi.cs.wpisuitetng.modules.core.models.UserDeserializer.java
License:Open Source License
/** * This static utility method takes a JSON string and attempts to * retrieve a password field from it. * @param serializedUser a JSON string containing a password * @return the password field parsed./*from www . j ava 2s .c o m*/ */ public static String parsePassword(String serializedUser) { if (!serializedUser.contains("password")) { throw new JsonParseException("The given JSON string did not contain a password field."); } int fieldStartIndex = serializedUser.indexOf("password"); int separator = serializedUser.indexOf(':', fieldStartIndex); int startIndex = serializedUser.indexOf('"', separator) + 1; int endIndex = serializedUser.indexOf('"', startIndex); String password = serializedUser.substring(startIndex, endIndex); return password; }
From source file:edu.wpi.cs.wpisuitetng.modules.defecttracker.models.DefectChangesetDeserializer.java
License:Open Source License
@Override public DefectChangeset deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { // hash map to hold the deserialized FieldChange objects HashMap<String, FieldChange<?>> changesMap = new HashMap<String, FieldChange<?>>(); JsonObject changeSet = json.getAsJsonObject(); if (changeSet.has("changes")) { JsonObject changes = changeSet.get("changes").getAsJsonObject(); if (changes.has("title")) { JsonObject titleObj = changes.get("title").getAsJsonObject(); String oldTitle = context.deserialize(titleObj.get("oldValue"), String.class); String newTitle = context.deserialize(titleObj.get("newValue"), String.class); changesMap.put("title", new FieldChange<String>(oldTitle, newTitle)); }/*from w ww .j a v a2 s. c o m*/ if (changes.has("description")) { JsonObject descriptionObj = changes.get("description").getAsJsonObject(); String oldDesc = context.deserialize(descriptionObj.get("oldValue"), String.class); String newDesc = context.deserialize(descriptionObj.get("newValue"), String.class); changesMap.put("description", new FieldChange<String>(oldDesc, newDesc)); } if (changes.has("assignee")) { JsonObject assigneeObj = changes.get("assignee").getAsJsonObject(); User oldUser = context.deserialize(assigneeObj.get("oldValue"), User.class); User newUser = context.deserialize(assigneeObj.get("newValue"), User.class); changesMap.put("assignee", new FieldChange<User>(oldUser, newUser)); } if (changes.has("tags")) { JsonObject tagsObj = changes.get("tags").getAsJsonObject(); Tag[] oldTags = context.deserialize(tagsObj.get("oldValue"), Tag[].class); Tag[] newTags = context.deserialize(tagsObj.get("newValue"), Tag[].class); changesMap.put("tags", new FieldChange<Set<Tag>>(new HashSet<Tag>(new ArrayList<Tag>(Arrays.asList(oldTags))), new HashSet<Tag>(new ArrayList<Tag>(Arrays.asList(newTags))))); } if (changes.has("status")) { JsonObject statusObj = changes.get("status").getAsJsonObject(); DefectStatus oldStatus = context.deserialize(statusObj.get("oldValue"), DefectStatus.class); DefectStatus newStatus = context.deserialize(statusObj.get("newValue"), DefectStatus.class); changesMap.put("status", new FieldChange<DefectStatus>(oldStatus, newStatus)); } // reconstruct the DefectChangeset DefectChangeset retVal = new DefectChangeset(); retVal.setChanges(changesMap); retVal.setDate((Date) (context.deserialize(changeSet.get("date"), Date.class))); retVal.setUser((User) (context.deserialize(changeSet.get("user"), User.class))); // return the DefectChangeset return retVal; } else { throw new JsonParseException("DefectChangeset type is unrecognized"); } }
From source file:edu.wpi.cs.wpisuitetng.modules.defecttracker.models.DefectEventDeserializer.java
License:Open Source License
@Override public DefectEvent deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { // we need to switch on the type field to figure out the concrete class to instantiate JsonObject object = element.getAsJsonObject(); if (!object.has("type")) { throw new JsonParseException("DefectEvent does not have type information"); }// w w w .jav a 2s.co m EventType eType = context.deserialize(object.get("type"), EventType.class); if (eType != null) { // type could be any garbage string, eType null if not in enum switch (eType) { case CHANGESET: return context.deserialize(element, DefectChangeset.class); case COMMENT: return context.deserialize(element, Comment.class); } } throw new JsonParseException("DefectEvent type is unrecognized"); }