-5

I have some Java code that has a String in the below format:

{username=username, password=password}

I want to convert it to JSON and pass it to a Http Post entity in an acceptable format. How do I do it?

Expected:

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

COde snippet:

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
mack
  • 345
  • 5
  • 18
  • 5
    This sounds like an XY problem. Where does that String comes from in the first place? My guess is that you're calling toString() on an object, and you're then trying to convert that string to JSON, instead of simply marshalling the object to JSON. – JB Nizet Nov 28 '17 at 20:25
  • @JBNizet- You are right. I am getting the Object from request.getBody(). Can you give me a working example of how do I send this to a HTTP Post entity as a application/json content. – mack Nov 28 '17 at 20:57
  • https://stackoverflow.com/questions/5101817/how-to-build-a-http-post-request-with-the-correct-entity-with-java-and-not-using – Marios Nikolaou Nov 28 '17 at 21:01
  • 1
    There are dozens of JSON parsers/marshallers, and of HTTP clients. It all depends on what you're using. – JB Nizet Nov 28 '17 at 21:01
  • @JBNizet - I am using HTTPClientBuilder to create my client to invoke the API. I have edited my question to give more detail on the code snippet – mack Nov 28 '17 at 21:15
  • HTTPClient doesn't have (AFAIK) any built-in JSON marshalling. So you need to pick one of the many JSON marshallers available. I like Jackson. – JB Nizet Nov 28 '17 at 21:18
  • @JBNizet please see the code snippet. Can you give me what and how can I fix this issue – mack Nov 28 '17 at 21:22
  • Well, you need to transform request.getBody() to JSON. toString() doesn't do that. So, once again, choose one of the many JSON marshallers available, read its documentation, and use it. I like Jackson. – JB Nizet Nov 28 '17 at 21:23
  • What is the output of getBody() – Marios Nikolaou Nov 28 '17 at 22:36

2 Answers2

0

I think the code below will be helpful.

Download the json jar files from here

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());
Marios Nikolaou
  • 1,326
  • 1
  • 13
  • 24
0

Jackson ObjectMapper helped me to iron out this issue.

mapper.writeValueAsString(myBean)

@JBNizet - thanks for the pointers.

mack
  • 345
  • 5
  • 18