0

So I've created a basic REST API in PHP that returns the following:

$result = array(
    "var" => 'testvalue',
);

sendResponse(200, json_encode($result));

How would I get this testvalue from the JSON using a HTTP POST request in Java?

I'm using the recommended answer from here currently: Sending HTTP POST Request In Java

But it dosn't show how to convert it from this stage:

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();

To a Java object.

So pretty much how to convert from JSON to a Java object.

Any ideas?

6
  • So do you want JSON data format to PHP ? Commented Oct 1, 2014 at 17:22
  • Why JSON is unusable format? Commented Oct 1, 2014 at 17:24
  • What do you mean by "But it dosn't show how to convert it from JSON to a usable format in Java"? Can you include example of results you get and what you would like to achieve? Commented Oct 1, 2014 at 17:25
  • So you are asking how to convert JSON string to Java objects ? Commented Oct 1, 2014 at 17:26
  • @user3420034 you can use GSON or Jackson. Commented Oct 1, 2014 at 17:29

1 Answer 1

1

If you do not need to read large data, you can use something like:

JSONObject json = new JSONObject(EntityUtils.toString(response.getEntity()));
String var = json.getString("var"):

You can use it on Android too, the library is org.json.JSONObject.

Sign up to request clarification or add additional context in comments.

3 Comments

It could be nice to mention from which library/package JSONObject comes from because it is not standard Java class.
@Pshemo org.json.JSONObject
It would be nice if you put that information with appropriate link to project site or jars (and/or maven dependency) to your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.