Effective conversion between Smile and JSON

advertisements

I've read that the conversion between Smile and JSON can be done efficiently in a few sources:

  • This means that conversion between JSON and Smile can be done efficiently and without loss of information. (github, jackson-docs);
  • The two formats are compatible: you can send Smile and decode as JSON, by wrapping the proper decoder. (stackoverflow)

And even Wikipedia: ... which means that tools that operate on JSON may be used with Smile as well, as long as proper encoder/decoder exists for tool to use

Unfortunately, I haven't find anything helpful in any of the sources except the information about encoder/decoder.

So the general question is how can this be done?

  • Is there some built-in way for doing this?
  • If not, are there some custom and already implemented solutions?
  • If not, please, give me a few hints about writing encoder/decoder.

I cannot assess how eficient this MO is, however, this simple straightforward way works fine: create a jackson mapper from SmileFactory, give it a JsonNode instance and have it map the input into a byte[] smile data:

public static void main(String[] args)
{
    ObjectMapper jsonMapper = new ObjectMapper();  // just for testing!
    ObjectMapper smileMapper = new ObjectMapper(new SmileFactory());

    // create json test data
    SmileDemo sd = new SmileDemo();
    System.out.println("ORIGINAL " + sd.str + " " + sd.i + " " + sd.flt + " " + sd.dbl  + " " + sd.bool + " " + sd.date);
    JsonNode json = jsonMapper.valueToTree(sd);
    try {
        // the following line is the actual conversion
        byte[] smileData = smileMapper.writeValueAsBytes(json);
        // test the conversion
        sd = smileMapper.readValue(smileData, SmileDemo.class);
        System.out.println("CONVERTED " + sd.str + " " + sd.i + " " + sd.flt + " " + sd.dbl  + " " + sd.bool + " " + sd.date);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static class SmileDemo
{
    public String str = "Hello World";
    public int i = 1000;
    public float flt = 1000.34F;
    public double dbl = 1000.34D;
    public boolean bool = false;
    public java.util.Date date = new Date(2016, 1, 1);
}