Fork me on GitHub

Decoding a json string into a POJO

To map a json string into a POJO, use this:


JSONAnnotationDecoder decoder = new JSONAnnotationDecoder();
AnnotatedSetTestClass result =
            decoder.decode(AnnotatedSetTestClass.class, "{\"test1\" : "OK"}");
result.getTest1() will return "OK" then.
            

Encoding a POJO to JSON


AnnotatedTestClass c = new AnnotatedTestClass();
JSONAnnotationEncoder encoder = new JSONAnnotationEncoder();
String json = encoder.encode(c);
      
The AnnotatedTestClass must have @JSON at the class top level and on any field or method which should be used for the JSON encoding. A field should be public or have appropriate getters.

Object API - Object to JSON


JSONObject o = new JSONObject();
o.put("mykey", new JSONString("myvalue"));
object.toJSON()
        
This will result in: {"mykey":"myvalue"}

Object API - JSON to Object

You can create JSONObjects from a JSON String too. As all classes from the API implement JSONValue, you will be mostly operating with that interface.
JSONDecoder decoder = new JSONDecoder("{\"key\":\"value\",\"key2\":{\"key3\":\"value2\"}}");
JSONValue result = decoder.decode();
TestCase.assertEquals("{\"key2\":{\"key3\":\"value2\"},\"key\":\"value\"}", result.toJSON());