Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing a simple JSON response in Java

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?

like image 746
Drew Noakes Avatar asked Dec 17 '12 11:12

Drew Noakes


3 Answers

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();
like image 194
Ilya Avatar answered Oct 13 '22 04:10

Ilya


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#.

like image 37
Shyamal Pandya Avatar answered Oct 13 '22 04:10

Shyamal Pandya


Have you looked at gson?

http://code.google.com/p/google-gson/

//Henrik

like image 20
Hiny Avatar answered Oct 13 '22 05:10

Hiny