将字符串格式化并编码为JSON

时间:2017-11-28 20:11:13

标签: java json

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

{username=username, password=password}

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

预期:

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

COde片段:

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

mapper.writeValueAsString(为myBean)

@JBNizet - 感谢指点。