Imagine a simple JSON response such as:
{
"success": false,
"message": "PEBKAC"
}
Given I have boolean
and String
variables, what's the simplest way to convert them to JSON in Java, without resorting to String.format
and friends.
I'm more familiar with C#, where this is quite straightforward using the built-in JavaScriptSerializer
class:
var success = false;
var message = "PEBKAC";
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(new { success, message });
Is there anything this straightforward for Java?
using JSON
serialization
org.json.JSONObject obj = new org.json.JSONObject();
obj.put("success", false);
obj.put("message", "PEBKAC");
obj.toString();
deserialization
org.json.JSONObject obj = new org.json.JSONObject(responseAsString);
obj.optBoolean("success"); // false
obj.optString("message"); // PEBKAC
using google-gson
public class MyObject
{
private String message;
private boolean success;
public MyObject(String message, boolean success)
{
this.message = message;
this.success = success;
}
}
serialization
MyObject obj = new MyObject("PEBKAC", false);
new com.google.gson.Gson().toJSON(obj);
deserialization
MyObject obj = new com.google.gson.Gson().fromJSON(responseAsString, MyObject.class);
obj.getMessage();
obj.getSuccess();
There are JSON parser libraries available, one of which is Jackson (http://jackson.codehaus.org). Jackson's ObjecMapper class (http://jackson.codehaus.org/1.9.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html) gives you functionality similar to the JavaScriptSerializer in C#.
Have you looked at gson?
http://code.google.com/p/google-gson/
//Henrik
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With