下面列出了com.google.gson.JsonParseException#getMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
return JsonUtil.deserializeToList(json, cls);
}
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 1);
else
return json;
}
else {
return JsonUtil.deserializeToObject(json, cls);
}
}
catch (JsonParseException e) {
throw new ApiException(500, e.getMessage());
}
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
return JsonUtil.deserializeToList(json, cls);
}
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 1);
else
return json;
}
else {
return JsonUtil.deserializeToObject(json, cls);
}
}
catch (JsonParseException e) {
throw new ApiException(500, e.getMessage());
}
}
/**
* Parse a piece of formatted text, which can be either plain text with legacy
* formatting codes, or JSON chat components.
*/
public static BaseComponent parseFormattedText(@Nullable Node node, BaseComponent def) throws InvalidXMLException {
if(node == null) return def;
// <blah translate="x"/> is shorthand for <blah>{"translate":"x"}</blah>
if(node.isElement()) {
final Attribute translate = node.asElement().getAttribute("translate");
if(translate != null) {
return new TranslatableComponent(translate.getValue());
}
}
String text = node.getValueNormalize();
if(looksLikeJson(text)) {
try {
return Components.concat(ComponentSerializer.parse(node.getValue()));
} catch(JsonParseException e) {
throw new InvalidXMLException(e.getMessage(), node, e);
}
} else {
return Components.concat(TextComponent.fromLegacyText(BukkitUtils.colorize(text)));
}
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
return JsonUtil.deserializeToList(json, cls);
}
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 1);
else
return json;
}
else {
return JsonUtil.deserializeToObject(json, cls);
}
}
catch (JsonParseException e) {
throw new ApiException(500, e.getMessage());
}
}
@Test
public void readAll() throws Exception {
SlackConfig testConfig = SlackTestConfig.get();
Gson gson = GsonFactory.createSnakeCase(testConfig);
List<Path> files = Files.list(Paths.get("../json-logs/samples/events")).collect(Collectors.toList());
for (Path jsonFile : files) {
String json = readWholeAsString(jsonFile);
String className = jsonFile.getFileName().toString().replaceFirst("\\.json$", "");
String fqdn = "com.slack.api.app_backend.events.payload." + className;
Class<EventsApiPayload<?>> clazz = (Class<EventsApiPayload<?>>) Class.forName(fqdn);
try {
EventsApiPayload<?> payload = gson.fromJson(json, clazz);
assertThat(payload, is(notNullValue()));
} catch (JsonParseException e) {
String message = "Check " + fqdn + " : " + e.getMessage();
throw new RuntimeException(message, e);
}
}
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
return JsonUtil.deserializeToList(json, cls);
}
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 1);
else
return json;
}
else {
return JsonUtil.deserializeToObject(json, cls);
}
}
catch (JsonParseException e) {
throw new ApiException(500, e.getMessage());
}
}
@Override
public Note get(String noteId, String notePath, AuthenticationInfo subject) throws IOException {
BlobId blobId = makeBlobId(noteId, notePath);
byte[] contents;
try {
contents = storage.readAllBytes(blobId);
} catch (StorageException se) {
throw new IOException("Could not read " + blobId.toString() + ": " + se.getMessage(), se);
}
try {
return Note.fromJson(new String(contents, encoding));
} catch (JsonParseException jpe) {
throw new IOException(
"Could note parse as json " + blobId.toString() + jpe.getMessage(), jpe);
}
}
@Override
public Note get(String noteId, AuthenticationInfo subject) throws IOException {
BlobId blobId = makeBlobId(noteId);
byte[] contents;
try {
contents = storage.readAllBytes(blobId);
} catch (StorageException se) {
throw new IOException("Could not read " + blobId.toString() + ": " + se.getMessage(), se);
}
try {
return Note.fromJson(new String(contents, encoding));
} catch (JsonParseException jpe) {
throw new IOException(
"Could note parse as json " + blobId.toString() + jpe.getMessage(), jpe);
}
}
private Object readTypeToken(TypeToken<?> token, HttpInputMessage inputMessage) throws IOException {
Reader json = new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));
try {
return this.gson.fromJson(json, token.getType());
}
catch (JsonParseException ex) {
throw new HttpMessageNotReadableException("JSON parse error: " + ex.getMessage(), ex);
}
}
@Override
public AuthenticationResponse handleResponse(final HttpResponse response) throws IOException {
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Charset charset = HTTP.DEF_CONTENT_CHARSET;
ContentType contentType = ContentType.get(response.getEntity());
if(contentType != null) {
if(contentType.getCharset() != null) {
charset = contentType.getCharset();
}
}
try {
final JsonObject json = JsonParser.parseReader(new InputStreamReader(response.getEntity().getContent(), charset)).getAsJsonObject();
final String token = json.getAsJsonPrimitive("token").getAsString();
final String endpoint = json.getAsJsonPrimitive("endpoint").getAsString();
return new AuthenticationResponse(response, token,
Collections.singleton(new Region(null, URI.create(endpoint), null, true)));
}
catch(JsonParseException e) {
throw new IOException(e.getMessage(), e);
}
}
else if(response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
|| response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
throw new AuthorizationException(new Response(response));
}
throw new GenericException(new Response(response));
}
private Object readTypeToken(TypeToken<?> token, HttpInputMessage inputMessage) throws IOException {
Reader json = new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));
try {
return this.gson.fromJson(json, token.getType());
}
catch (JsonParseException ex) {
throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
}
}
public static ProjectConfig parse(String configText) throws InvalidProject {
ProjectConfig config = null;
if (configText != null) {
try {
JsonReader configReader = new JsonReader(new StringReader(configText));
configReader.setLenient(true);
JsonElement configJsonElement = new JsonParser().parse(configReader);
if (configJsonElement != null) {
// Config files often contain JavaScript idioms like comments, single quoted strings,
// and trailing commas in lists.
// Check that the JSON parsed from configText is structurally the same as that
// produced when it is interpreted by GSON in lax mode.
String normalConfigText = JsonSanitizer.sanitize(configText);
JsonElement normalConfigJsonElement = new JsonParser().parse(normalConfigText);
JsonStructureChecker.requireSimilar(configJsonElement, normalConfigJsonElement);
Gson gson = GsonModule.provideGson(); // TODO(user): Remove this static reference.
config = gson.fromJson(configText, ProjectConfig.class);
}
} catch (JsonParseException e) {
throw new InvalidProject(e, "Could not parse MOE config: " + e.getMessage());
}
}
if (config == null) {
throw new InvalidProject("Could not parse MOE config");
}
config.validate();
return config;
}
private <T> T safeFromJson(String json, Type typeOfT) throws ApiException {
try {
return gson.fromJson(json, typeOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
private <T> T safeFromJson(String json, Class<T> classOfT) throws ApiException {
try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
@Override
public Object convertFromInternal(Message<?> message, Class<?> targetClass) {
TypeToken<?> token = getTypeToken(targetClass);
Object payload = message.getPayload();
Charset charset = getCharset(getMimeType(message.getHeaders()));
Reader reader;
if (payload instanceof byte[]) {
reader = new InputStreamReader(new ByteArrayInputStream((byte[]) payload), charset);
} else {
reader = new StringReader((String) payload);
}
try {
return this.gson.fromJson(reader, token.getType());
} catch (JsonParseException ex) {
throw new MessageConversionException(message, "Could not read JSON: " + ex.getMessage(), ex);
}
}