Java Code Examples for com.google.gson.JsonParseException#getMessage()

The following examples show how to use com.google.gson.JsonParseException#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApiInvoker.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
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());
  }
}
 
Example 2
Source File: ApiInvoker.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
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());
  }
}
 
Example 3
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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)));
    }
}
 
Example 4
Source File: ApiInvoker.java    From swaggy-jenkins with MIT License 6 votes vote down vote up
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());
  }
}
 
Example 5
Source File: SamplePayloadParsingTest.java    From java-slack-sdk with MIT License 6 votes vote down vote up
@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);
        }
    }
}
 
Example 6
Source File: ApiInvoker.java    From swagger-aem with Apache License 2.0 6 votes vote down vote up
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());
  }
}
 
Example 7
Source File: GCSNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 8
Source File: OldGCSNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 9
Source File: GsonHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
	}
}
 
Example 10
Source File: HubicAuthenticationResponseHandler.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@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));
}
 
Example 11
Source File: GsonHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 12
Source File: ProjectConfig.java    From MOE with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: HueBridge.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
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());
    }
}
 
Example 14
Source File: HueBridge.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
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());
    }
}
 
Example 15
Source File: GsonMessageConverter.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@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);
    }
}