下面列出了java.security.spec.ECGenParameterSpec#com.google.gson.JsonParseException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jObject = (JsonObject) json;
Location location = new Location(jObject.get("Provider").getAsString());
location.setTime(jObject.get("Time").getAsLong());
location.setLatitude(jObject.get("Latitude").getAsDouble());
location.setLongitude(jObject.get("Longitude").getAsDouble());
if (jObject.has("Altitude"))
location.setAltitude(jObject.get("Altitude").getAsDouble());
if (jObject.has("Speed"))
location.setSpeed(jObject.get("Speed").getAsFloat());
if (jObject.has("Bearing"))
location.setBearing(jObject.get("Bearing").getAsFloat());
if (jObject.has("Accuracy"))
location.setAccuracy(jObject.get("Accuracy").getAsFloat());
return location;
}
@Override
public List<AllocatedGroupRange> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
final List<AllocatedGroupRange> groupRanges = new ArrayList<>();
try {
if(json.isJsonArray()) {
final JsonArray jsonObject = json.getAsJsonArray();
for (int i = 0; i < jsonObject.size(); i++) {
final JsonObject unicastRangeJson = jsonObject.get(i).getAsJsonObject();
final int lowAddress = unicastRangeJson.get("lowAddress").getAsInt();
final int highAddress = unicastRangeJson.get("highAddress").getAsInt();
groupRanges.add(new AllocatedGroupRange(lowAddress, highAddress));
}
}
} catch (Exception ex) {
Log.e(TAG, "Error while de-serializing Allocated group range: " + ex.getMessage());
}
return groupRanges;
}
public void testCustomDeserializationUsingWithoutUsingMobileServiceTable() {
String serializedObject = "{\"address\":{\"zipcode\":1313,\"country\":\"US\",\"streetaddress\":\"1345 Washington St\"},\"firstName\":\"John\",\"lastName\":\"Doe\"}";
JsonObject jsonObject = new JsonParser().parse(serializedObject).getAsJsonObject();
gsonBuilder.registerTypeAdapter(Address.class, new JsonDeserializer<Address>() {
@Override
public Address deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
Address a = new Address(arg0.getAsJsonObject().get("streetaddress").getAsString(), arg0.getAsJsonObject().get("zipcode").getAsInt(), arg0
.getAsJsonObject().get("country").getAsString());
return a;
}
});
ComplexPersonTestObject deserializedPerson = gsonBuilder.create().fromJson(jsonObject, ComplexPersonTestObject.class);
// Asserts
assertEquals("John", deserializedPerson.getFirstName());
assertEquals("Doe", deserializedPerson.getLastName());
assertEquals(1313, deserializedPerson.getAddress().getZipCode());
assertEquals("US", deserializedPerson.getAddress().getCountry());
assertEquals("1345 Washington St", deserializedPerson.getAddress().getStreetAddress());
}
@Override
public List<AllocatedGroupRange> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
final List<AllocatedGroupRange> groupRanges = new ArrayList<>();
try {
final JsonArray jsonObject = json.getAsJsonArray();
for (int i = 0; i < jsonObject.size(); i++) {
final JsonObject unicastRangeJson = jsonObject.get(i).getAsJsonObject();
final int lowAddress = Integer.parseInt(unicastRangeJson.get("lowAddress").getAsString(), 16);
final int highAddress = Integer.parseInt(unicastRangeJson.get("highAddress").getAsString(), 16);
groupRanges.add(new AllocatedGroupRange(lowAddress, highAddress));
}
} catch (Exception ex) {
Log.e(TAG, "Error while de-serializing Allocated group range: " + ex.getMessage());
}
return groupRanges;
}
protected Set<Map.Entry<String, JsonElement>> parseStoreToImagesMap(String storeName)
throws IOException, InterruptedException {
GHMyself myself = dockerfileGitHubUtil.getMyself();
String login = myself.getLogin();
GHRepository store = dockerfileGitHubUtil.getRepo(Paths.get(login, storeName).toString());
GHContent storeContent = dockerfileGitHubUtil.tryRetrievingContent(store, Constants.STORE_JSON_FILE,
store.getDefaultBranch());
if (storeContent == null) {
return Collections.emptySet();
}
JsonElement json;
try (InputStream stream = storeContent.read(); InputStreamReader streamR = new InputStreamReader(stream)) {
try {
json = JsonParser.parseReader(streamR);
} catch (JsonParseException e) {
log.warn("Not a JSON format store.");
return Collections.emptySet();
}
}
JsonElement imagesJson = json.getAsJsonObject().get("images");
return imagesJson.getAsJsonObject().entrySet();
}
public static JsonObject buildJsonObject(String json) throws ParsingException {
if (json == null) {
throw new ParsingException("Cannot parse empty json");
}
JsonReader reader = new JsonReader(new StringReader(json));
reader.setLenient(true);
try {
JsonElement jRawSource = new JsonParser().parse(reader);
if (jRawSource != null && jRawSource.isJsonObject()) {
return jRawSource.getAsJsonObject();
} else {
throw new ParsingException("The incoming Json is bad/malicious");
}
} catch (JsonParseException e) {
throw new ParsingException("The incoming Json is bad/malicious");
}
}
@Override
public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = jsonElement.getAsJsonObject();
if (!jsonObject.has("type")) {
throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object");
}
final String routingConfigType = jsonObject.get("type").getAsString();
if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) {
return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class);
} else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) {
return context.deserialize(jsonElement, RoutingTableRoutingConfig.class);
}
throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\"");
}
/**
* Deserialize the given JSON string to Java object.
*
* @param <T> Type
* @param body The JSON string
* @param returnType The type to deserialize into
* @return The deserialized Java object
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
try {
if (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;
if (returnType.equals(String.class))
return (T) body;
else throw e;
}
}
public Balances deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Balances balances = new Balances();
if (json.isJsonObject()) {
JsonObject o = json.getAsJsonObject();
List<Market> markets = new ArrayList<Market>();
Iterator<Entry<String, JsonElement>> iter = o.entrySet()
.iterator();
while (iter.hasNext()) {
Entry<String, JsonElement> jsonOrder = iter.next();
String currency = jsonOrder.getKey();
double balance = context.deserialize(jsonOrder.getValue(),
Double.class);
balances.put(currency, balance);
}
}
return balances;
}
@Override
public Date deserialize(JsonElement element, Type type, JsonDeserializationContext context)
throws JsonParseException {
String date = element.getAsString();
@SuppressLint("SimpleDateFormat")
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return formatter.parse(date);
} catch (ParseException e) {
Log.e(TAG, "Parsing failed: " + Log.getStackTraceString(e));
return new Date();
}
}
@Override
public JsonMessage decode(MqttMessage msg) throws MalformedMessageException {
JsonObject data;
if (msg.getPayload().length == 0) {
data = null;
} else {
try {
final String payloadInString = new String(msg.getPayload(), "UTF8");
data = JSON_PARSER.parse(payloadInString).getAsJsonObject();
} catch (JsonParseException | UnsupportedEncodingException e) {
throw new MalformedMessageException("Unable to parse JSON: " + e.toString());
}
}
return new JsonMessage(data, null);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
logger.error("Error in session {}: {}", session.getId(), exception.getMessage());
if (exception.getMessage().contains("Connection reset by peer")) {
afterConnectionClosed(session, CloseStatus.SESSION_NOT_RELIABLE);
return;
}
JsonMessageBuilder builder;
session = sessionMonitor.getSession(session.getId());
if (exception instanceof JsonParseException) {
builder = JsonMessageBuilder
.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, "Incorrect JSON syntax");
} else {
builder = JsonMessageBuilder
.createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
}
try {
session.sendMessage(new TextMessage(GsonFactory.createGson().toJson(builder.build())));
} catch (ClosedChannelException closedChannelException) {
logger.error("WebSocket error: Channel is closed");
}
}
/**
* post-loading initialization hook.
*/
void initialize() {
if (parameters == null) {
throw new JsonParseException("Animation State Machine should contain \"parameters\" key.");
}
if (clips == null) {
throw new JsonParseException("Animation State Machine should contain \"clips\" key.");
}
if (states == null) {
throw new JsonParseException("Animation State Machine should contain \"states\" key.");
}
if (transitions == null) {
throw new JsonParseException("Animation State Machine should contain \"transitions\" key.");
}
shouldHandleSpecialEvents = true;
lastPollTime = Float.NEGATIVE_INFINITY;
// setting the starting state
IClip state = clips.get(startState);
if (!clips.containsKey(startState) || !states.contains(startState)) {
throw new IllegalStateException("unknown state: " + startState);
}
currentStateName = startState;
currentState = state;
}
@Override
public WindowProperties deserialize(
final JsonElement json,
final Type typeOfT,
final JsonDeserializationContext context) throws JsonParseException {
final WindowProperties properties = new WindowProperties();
if (json.isJsonObject()) {
final JsonObject map = json.getAsJsonObject();
if (map.has(WIDTH_KEY))
properties.widthProperty.set(map.get(WIDTH_KEY).getAsInt());
if (map.has(HEIGHT_KEY))
properties.heightProperty.set(map.get(HEIGHT_KEY).getAsInt());
if (map.has(IS_FULL_SCREEN_KEY))
properties.isFullScreen.set(map.get(IS_FULL_SCREEN_KEY).getAsBoolean());
properties.clean();
}
return properties;
}
@Override
public LookupSwitchInsnNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = (JsonObject) json;
LabelNode dflt = context.deserialize(jsonObject.get("dflt"), LabelNode.class);
List<Integer> keysList = context.deserialize(jsonObject.get("keys"), List.class);
List<LabelNode> labelsList = context.deserialize(jsonObject.get("labels"), List.class);
int[] keys = new int[keysList.size()];
for(int i=0; i < keys.length; i++){
keys[i] = keysList.get(i);
}
LabelNode[] labels = new LabelNode[labelsList.size()];
for(int i=0; i < labels.length; i++){
labels[i] = labelsList.get(i);
}
return new LookupSwitchInsnNode(dflt, keys, labels);
}
@SuppressWarnings("unchecked")
private Class<T> getClassInstance() {
@SuppressWarnings("unchecked")
final String className = (String) config.get(SidelineConfig.FILTER_CHAIN_STEP_CLASS);
Preconditions.checkArgument(
className != null && !className.isEmpty(),
"A valid class name must be specified for " + SidelineConfig.FILTER_CHAIN_STEP_CLASS
);
try {
return (Class<T>) Class.forName(className);
} catch (ClassNotFoundException cnfe) {
throw new JsonParseException(cnfe.getMessage());
}
}
@Override
@Nullable
public Feature deserialize(@Nonnull JsonElement json, @Nonnull Type typeOfT, @Nonnull JsonDeserializationContext context)
throws JsonParseException {
try {
JsonObject jsonObject = json.getAsJsonObject();
// default path
String name = jsonObject.get("name").getAsString();
if (!name.contains(".")) {
name = DEFAULT_PATH + "." + name;
}
Class<?> clazz = Class.forName(name);
Feature feature = context.deserialize(json, clazz);
injector.injectMembers(feature);
return feature;
} catch (Exception e) {
log.log(Level.WARNING, "Could not deserialize feature:\n" + json.toString(), e);
}
return null;
}
public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) {
if (vm == null || !VirtualMachine.Type.User.equals(vm.getType()) || Strings.isNullOrEmpty(rootVolChainInfo)) {
return;
}
String rootDiskController = null;
try {
final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class);
if (infoInChain != null) {
rootDiskController = infoInChain.getControllerFromDeviceBusName();
}
final UserVmVO userVmVo = _userVmDao.findById(vm.getId());
if ((rootDiskController != null) && (!rootDiskController.isEmpty())) {
_userVmDao.loadDetails(userVmVo);
_userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController);
}
} catch (JsonParseException e) {
s_logger.debug("Error parsing chain info json: " + e.getMessage());
}
}
@Override
public Pair<Long, Long> deserialize(JsonElement json, java.lang.reflect.Type type, JsonDeserializationContext context) throws JsonParseException {
Pair<Long, Long> pairs = new Pair<Long, Long>(null, null);
JsonArray array = json.getAsJsonArray();
if (array.size() != 2) {
return pairs;
}
JsonElement element = array.get(0);
if (!element.isJsonNull()) {
pairs.first(element.getAsLong());
}
element = array.get(1);
if (!element.isJsonNull()) {
pairs.second(element.getAsLong());
}
return pairs;
}
/**
* Processes a DELETE request
*
* @param req the request object
* @param res the response object
* @param user the authorized user
* @return the result JSON object
*/
public static Object delete(Request req, Response res, User user) {
List<Long> ids;
try {
ids = Arrays.asList(GSON.fromJson(req.body(), Long[].class));
}
catch (JsonParseException e) {
Spark.halt(HttpStatus.SC_BAD_REQUEST);
return null;
}
List<ImageProfile> profiles =
ImageProfileFactory.lookupByIdsAndOrg(ids, user.getOrg());
if (profiles.size() < ids.size()) {
return json(res, ResultJson.error("not_found"));
}
profiles.forEach(ImageProfileFactory::delete);
return json(res, ResultJson.success(profiles.size()));
}
/**
* Download a subreddit's usernotes
*
* @param subreddit
*/
public static void downloadUsernotes(String subreddit) {
WikiManager manager = new WikiManager(Authentication.reddit);
Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<Map<String, List<Usernote>>>() {}.getType(),
new Usernotes.BlobDeserializer()).create();
try {
String data = manager.get(subreddit, "usernotes").getContent();
Usernotes result = gson.fromJson(data, Usernotes.class);
cache.edit().putLong(subreddit + "_usernotes_timestamp", System.currentTimeMillis()).apply();
if (result != null && result.getSchema() == 6) {
result.setSubreddit(subreddit);
notes.put(subreddit, result);
cache.edit().putBoolean(subreddit + "_usernotes_exists", true)
.putString(subreddit + "_usernotes_data", data).apply();
} else {
cache.edit().putBoolean(subreddit + "_usernotes_exists", false).apply();
}
} catch (NetworkException | JsonParseException e) {
if (e instanceof JsonParseException) {
notes.remove(subreddit);
}
cache.edit().putLong(subreddit + "_usernotes_timestamp", System.currentTimeMillis())
.putBoolean(subreddit + "_usernotes_exists", false).apply();
}
}
@Override
public Ecosystem deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
long size = jsonObject.get("size").getAsLong();
Ecosystem result = new Ecosystem(size, false);
JsonArray foodPellets = jsonObject.get("foodPellets").getAsJsonArray();
for (int i = 0; i < foodPellets.size(); i++) {
JsonElement jsonFoodPellet = foodPellets.get(i);
FoodPellet foodPellet = context.deserialize(jsonFoodPellet, FoodPellet.class);
result.insert(foodPellet);
}
JsonArray eggs = jsonObject.get("eggs").getAsJsonArray();
for (int i = 0; i < eggs.size(); i++) {
JsonElement jsonEgg = eggs.get(i);
Egg egg = context.deserialize(jsonEgg, Egg.class);
result.insert(egg);
}
JsonArray narjillos = jsonObject.get("narjillos").getAsJsonArray();
for (int i = 0; i < narjillos.size(); i++) {
JsonElement jsonNarjllo = narjillos.get(i);
Narjillo narjillo = context.deserialize(jsonNarjllo, Narjillo.class);
result.insert(narjillo);
}
JsonElement jsonAtmosphere = jsonObject.get("atmosphere");
Atmosphere atmosphere = context.deserialize(jsonAtmosphere, Atmosphere.class);
result.setAtmosphere(atmosphere);
return result;
}
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
// do nothing
}
}
throw new JsonParseException("Unparsable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
/**
* Deserializes JSON and converts it to the appropriate {@link QueryAggregation} subclass.
*
* @param json the JSON data being deserialized
* @param typeOfT the type to deserialize to, which should be {@link QueryAggregation}
* @param context additional information about the deserialization state
* @return the appropriate {@link QueryAggregation} subclass
* @throws JsonParseException signals that there has been an issue parsing the JSON
*/
@Override
public QueryAggregation deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
// get aggregation type from response
JsonObject jsonObject = json.getAsJsonObject();
String aggregationType = "";
for (String key : jsonObject.keySet()) {
if (key.equals(TYPE)) {
aggregationType = jsonObject.get(key).getAsString();
}
}
QueryAggregation aggregation;
if (aggregationType.equals(AggregationType.HISTOGRAM.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Histogram.class);
} else if (aggregationType.equals(AggregationType.MAX.getName())
|| aggregationType.equals(AggregationType.MIN.getName())
|| aggregationType.equals(AggregationType.AVERAGE.getName())
|| aggregationType.equals(AggregationType.SUM.getName())
|| aggregationType.equals(AggregationType.UNIQUE_COUNT.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Calculation.class);
} else if (aggregationType.equals(AggregationType.TERM.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Term.class);
} else if (aggregationType.equals(AggregationType.FILTER.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Filter.class);
} else if (aggregationType.equals(AggregationType.NESTED.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Nested.class);
} else if (aggregationType.equals(AggregationType.TIMESLICE.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Timeslice.class);
} else if (aggregationType.equals(AggregationType.TOP_HITS.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, TopHits.class);
} else {
aggregation = GsonSingleton.getGson().fromJson(json, GenericQueryAggregation.class);
}
return aggregation;
}
/**
* Parses a given JSON String as JsonArray.
* @param jsonString the JSON string
* @return the JsonArray
* @throws JsonException in case of errors
*/
public static JsonArray parseAsJsonArray(String jsonString) throws JsonException {
try {
return JsonParser.parseString(jsonString).getAsJsonArray();
} catch (JsonParseException | IllegalStateException ex) {
throw new JsonException("Unable to parse as JsonArray: " + jsonString, ex);
}
}
@Override
public Payload deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
Payload payload = new Payload();
JsonElement element = jsonObject.get("scp");
if (element != null) {
if (element.isJsonArray()) {
for (JsonElement item : element.getAsJsonArray()) {
payload.scopes.add(item.getAsString());
}
} else {
payload.scopes.add(element.getAsString());
}
}
payload.jti = jsonObject.get("jti").getAsString();
payload.kid = jsonObject.get("kid").getAsString();
payload.sub = jsonObject.get("sub").getAsString();
try {
payload.characterID = Integer.valueOf(payload.sub.substring("CHARACTER:EVE:".length()));
} catch (NumberFormatException ex) {
payload.characterID = null;
}
payload.azp = jsonObject.get("azp").getAsString();
payload.name = jsonObject.get("name").getAsString();
payload.owner = jsonObject.get("owner").getAsString();
payload.jti = jsonObject.get("jti").getAsString();
payload.exp = jsonObject.get("exp").getAsString();
payload.iss = jsonObject.get("iss").getAsString();
return payload;
}
@Override
public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if (!(json instanceof JsonPrimitive)) {
throw new JsonParseException("The date should be a string value");
}
try {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date) format.parse(json.getAsString());
return new Timestamp(date.getTime());
} catch (Exception e) {
throw new JsonParseException(e);
}
}
@Override
public Key.ComplexKey deserialize(JsonElement json, java.lang.reflect.Type typeOfT,
JsonDeserializationContext context) throws
JsonParseException {
if (json.isJsonArray()) {
ComplexKey key = new ComplexKey(json.getAsJsonArray());
return key;
} else {
return null;
}
}
@Override
public BaseComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonPrimitive()) {
return new TextComponent(json.getAsString());
}
JsonObject object = json.getAsJsonObject();
if (object.has("translate")) {
return (BaseComponent)context.deserialize(json, TranslatableComponent.class);
}
return (BaseComponent)context.deserialize(json, TextComponent.class);
}
public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (!(json instanceof JsonPrimitive)) {
throw new JsonParseException("The date should be a string value");
}
try {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date) format.parse(json.getAsString());
return new Timestamp(date.getTime());
} catch (Exception e) {
throw new JsonParseException(e);
}
}