【问题标题】:Formatting and encoding a string to JSON将字符串格式化和编码为 JSON
【发布时间】:2017-11-28 20:11:12
【问题描述】:

我有一些具有以下格式的字符串的 Java 代码:

{username=username, password=password}

我想将其转换为 JSON 并以可接受的格式将其传递给 Http Post 实体。我该怎么做?

预期:

{
  "username": "username",
  "password": "password"
}  

代码sn-p:

HttpClient httpClient = HttpClientBuilder.create().build();
 HttpPost postRequest = new HttpPost(
                            "https://url/api/v1/chk");
    StringEntity input = new StringEntity(request.getBody().toString());  // I am sending an aplication/json content type JSON  to the API that is invoking the https://url/api/v1/chk API                  input.setContentType("application/json");
    postRequest.setEntity(input);HttpResponse response = httpClient.execute(postRequest); // This throws 400 bad request

【问题讨论】:

  • 这听起来像是一个 XY 问题。该字符串首先来自哪里?我的猜测是你在一个对象上调用 toString(),然后你试图将该字符串转换为 JSON,而不是简单地将对象编组为 JSON。
  • @JBNizet-你是对的。我从 request.getBody() 获取对象。您能给我一个工作示例,说明如何将其作为应用程序/json 内容发送到 HTTP Post 实体。
  • 有几十个 JSON 解析器/编组器和 HTTP 客户端。这完全取决于您使用的是什么。
  • @JBNizet - 我正在使用 HTTPClientBuilder 创建我的客户端来调用 API。我已经编辑了我的问题以提供有关代码 sn-p 的更多详细信息

标签: java json


【解决方案1】:

我认为下面的代码会有所帮助。

here下载json jar文件

import com.google.gson.JsonParser;
import com.google.gson.JsonObject;

JsonObject jsonObject = new JsonParser().parse("{username=Mario, password=1234}").getAsJsonObject();
System.out.println(jsonObject.get("username").getAsString());

【讨论】:

    【解决方案2】:

    Jackson ObjectMapper 帮助我解决了这个问题。

    mapper.writeValueAsString(myBean)

    @JBNizet - 感谢您的指点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多