Groovy web console

subscribe to the feed Subscribe
to this
site
custom json deserializer (via #groovywebconsole)
tweet this snippet Tweet
this
script

custom json deserializer

Published 2 months ago by dsharew with tags json deserializer custom groovy
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.*;
import groovy.transform.Field;
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface JsonDeserializer {
String[] names() default []
}

class WeatherRow{

@JsonDeserializer(names = ["mintemp"])
String mintemp;

@JsonDeserializer(names = ["mintemp"])
String minTemp;

@JsonDeserializer(names = ["mintemp"])
String numberOfPonies;


static WeatherRow fromJson(def jsonObject){

    WeatherRow weatherRow = new WeatherRow();
   try{
       weatherRow = new WeatherRow(jsonObject);
      }catch(MissingPropertyException ex){
      //swallow missing property exception.
      }

   WeatherRow.class.getDeclaredFields().each{

       def jsonDeserializer = it.getDeclaredAnnotations()?.find{it.annotationType() == JsonDeserializer}
       def fieldNames = [];

       fieldNames << it.name;

       if(jsonDeserializer){
        fieldNames.addAll(jsonDeserializer.names());

        fieldNames.each{i ->
            if(jsonObject."$i")//TODO: if field type is not String type custom parsing here.
                weatherRow."${it.name}" = jsonObject."$i";
        }

       }

    };

return weatherRow;

}


}



def testJsonStr = '''
{
    "days": [
        {
            "mintemp": "21.8"
        }
    ]
}'''

def parsedWeatherRows = new JsonSlurper().parseText(testJsonStr);

assert WeatherRow.fromJson(parsedWeatherRows.days[0]).mintemp == "21.8"
assert WeatherRow.fromJson(parsedWeatherRows.days[0]).minTemp == "21.8"
assert WeatherRow.fromJson(parsedWeatherRows.days[0]).numberOfPonies == "21.8"