Java 尝试发送post rquest时获取无效json错误

Java 尝试发送post rquest时获取无效json错误,java,json,parsing,post,gson,Java,Json,Parsing,Post,Gson,我有一个JSON字符串,我使用下面的GSON库将其转换为JSON: Gson g = new Gson(); String json = "{\"user\":\"c8689ls8-7da5-4ac8-8afa-5casdf623302\",\"pass\":\"22Lof7w9-2b8c-45fa-b619-12cf27dj386\"}"; DataOutputStream out = new

我有一个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();
但是,当我发送实际post请求时,会收到以下错误消息:

{"message":"Invalid JSON: Unexpected string literal\n at [Source: UNKNOWN; line: 1, column: 108]","_links":{"self":{"href":"/endpoint","templated":false}}}
我不确定我的JSON字符串有什么问题,因为它看起来格式正确,后来被转换成JSON。这个错误的原因是什么

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);

我认为22Lof7w9-2b8c-45fa-b619-12cf27dj386也必须在引号中。22Lof7w9-2b8c-45fa-b619-12cf27dj386@JCWasmx86我编辑了上面的代码,让它在引号中,但我仍然得到相同的错误什么是g?为了获得更好的帮助,发布最小的代码-没有任何不相关的部分,但仍然完整-这样我们就可以将其复制并粘贴到我们的机器上,并且无需任何修改就可以运行它以获得与所述完全相同的问题。@Pshemo如描述中所述,我使用GSON库将字符串转换为json。g只是GSON的一个新实例。更新了代码以使其更清晰,但是您能澄清一下您在这里想做什么吗?在这个问题上,您已经有了JSON字符串,我假设您的API应该发送给客户机,那么您在g.toJsonjson上想要实现什么呢?你想要什么?写字节。。确切地发送?或者因为OP已经有了JSON字符串,只需发送该字符串,而不需要再次尝试将其转换为JSON字符串..是的@Pshemo,但我认为他可能试图将其序列化为对象,也许?