【问题标题】:Getting invalid json error when trying to send post rquest尝试发送发布请求时出现无效的 json 错误
【发布时间】:2020-12-04 15:38:09
【问题描述】:

我有一个 JSON 字符串,我使用下面的 GSON 库将其转换为 JSON:

Gson g = new Gson();
String json = "{\"user\":\"c8689ls8-7da5-4ac8-8afa-5casdf623302\",\"pass\":\"22Lof7w9-2b8c-45fa-b619-12cf27dj386\"}";
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(g.toJson(json));
out.flush();
out.close();

但是,当我发送实际的发布请求时,我收到以下错误消息:

{"message":"Invalid JSON: Unexpected string literal\n at [Source: UNKNOWN; line: 1, column: 108]","_links":{"self":{"href":"/endpoint","templated":false}}}

我不确定我的 JSON 字符串有什么问题,因为它看起来格式正确,后来转换为 JSON。这个错误的原因是什么?

【问题讨论】:

  • 我认为22Lof7w9-2b8c-45fa-b619-12cf27dj386 也必须用引号引起来。 ("22Lof7w9-2b8c-45fa-b619-12cf27dj386")
  • @JCWasmx86 我编辑了上面的代码,让它用引号引起来,但我仍然得到同样的错误
  • 什么是g?为了获得更好的帮助,发布minimal reproducible example(最少的代码 - 没有任何不相关的部分,但仍然完整 - 因此我们可以将其复制并粘贴到我们的机器上,无需任何修改运行它以获得完全相同的问题有问题的描述)。
  • @Pshemo 如描述中所述,我使用 GSON 库将字符串转换为 json。 g 只是 GSON 的一个新实例。更新代码使其更清晰
  • 但是你能澄清一下你想在这里做什么吗?有问题你已经有 JSON 字符串(我假设你的 API 应该发送给客户端),那么你想在g.toJson(json) 上实现什么?您希望out.writeBytes(..) 准确发送什么?

标签: java json parsing post gson


【解决方案1】:
This method serializes the specified object into its equivalent Json representation.
   * This method should be used when the specified object is not a generic type. This method uses
   * {@link Class#getClass()} to get the type for the specified object, but the
   * {@code getClass()} loses the generic type information because of the Type Erasure feature
   * of Java. Note that this method works fine if the any of the object fields are of generic type,
   * just the object itself should not be of a generic type. If the object is of generic type, use
   * {@link #toJson(Object, Type)} instead. If you want to write out the object to a
   * {@link Writer}, use {@link #toJson(Object, Appendable)} instead.
   *
   * @param src the object for which Json representation is to be created setting for Gson
   * @return Json representation of {@code src}.
   */
  public String toJson(Object src) {
    if (src == null) {
      return toJson(JsonNull.INSTANCE);
    }
    return toJson(src, src.getClass());
  }

它的意思是获取一个对象实例,并将其转换为json字符串格式。

您要做的是将 JSON 字符串传递给该方法。它不会工作


你想要的是

gson.fromJson("yourStringJSONHere", YourClassWhichMatchesJSONVariables.class)

或者,如果您没有映射到 JSON 的类,而只是想要一个通用的:

JsonElement jelement = new JsonParser().parse(yourJSONString);

JSON parsing using Gson for Java

【讨论】:

  • 或者因为 OP 已经有 JSON 字符串,所以只需发送该字符串 而不 尝试再次将其转换为 JSON 字符串..
  • 是的@Pshemo,但我认为他可能试图将它序列化为一个对象,也许?
猜你喜欢
  • 2015-05-29
  • 2019-10-10
  • 2019-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多