尝试发送post rquest时出现无效的json错误

4zcjmb1e  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(320)

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

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

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

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

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

u4vypkhs

u4vypkhs1#

  1. This method serializes the specified object into its equivalent Json representation.
  2. * This method should be used when the specified object is not a generic type. This method uses
  3. * {@link Class#getClass()} to get the type for the specified object, but the
  4. * {@code getClass()} loses the generic type information because of the Type Erasure feature
  5. * of Java. Note that this method works fine if the any of the object fields are of generic type,
  6. * just the object itself should not be of a generic type. If the object is of generic type, use
  7. * {@link #toJson(Object, Type)} instead. If you want to write out the object to a
  8. * {@link Writer}, use {@link #toJson(Object, Appendable)} instead.
  9. *
  10. * @param src the object for which Json representation is to be created setting for Gson
  11. * @return Json representation of {@code src}.
  12. */
  13. public String toJson(Object src) {
  14. if (src == null) {
  15. return toJson(JsonNull.INSTANCE);
  16. }
  17. return toJson(src, src.getClass());
  18. }

它意味着获取一个对象示例,并将其转换为json字符串格式。
您要做的是将一个json字符串传递到该方法中。这行不通
你想要的是

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

或者,如果您没有Map到json的类,只需要一个泛型类:

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

使用gson for java解析json

展开查看全部

相关问题