java - How to custom deserialize from array in Jackson? -
i serialize / deserialize (joda) date array.
unfortunately, can't figure out how deserializtion part:
import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.jsondeserialize; import com.fasterxml.jackson.databind.annotation.jsonserialize; import org.joda.time.localdate; import org.joda.time.localtime; import java.io.ioexception; public class tryjodatime { public static class localtimeserializer extends jsonserializer<localtime> { @override public void serialize(localtime value, jsongenerator gen, serializerprovider serializers) throws ioexception, jsonprocessingexception { gen.writestartarray(); gen.writenumber(value.gethourofday()); gen.writenumber(value.getminuteofhour()); gen.writenumber(value.getsecondofminute()); gen.writenumber(value.getmillisofsecond()); gen.writeendarray(); } } public static class localtimedeserializer extends jsondeserializer<localtime> { @override public localtime deserialize(jsonparser jp, deserializationcontext ctxt) throws ioexception, jsonprocessingexception { jsontoken token; token = jp.nexttoken(); if( token != jsontoken.start_array ) { throw new jsonparseexception("start array expected", jp.getcurrentlocation()); } int hour = jp.nextintvalue(0); int minute = jp.nextintvalue(0); int second = jp.nextintvalue(0); int ms = jp.nextintvalue(0); token = jp.nexttoken(); if( token != jsontoken.end_array ) { throw new jsonparseexception("end array expected", jp.getcurrentlocation()); } return new localtime(hour, minute, second, ms); } } public static class myclass { private localtime localtime; public myclass() { localtime = localtime.now(); } @jsonserialize(using = localtimeserializer.class) public localtime getlocaltime() { return localtime; } @jsondeserialize(using = localtimedeserializer.class) public void setlocaltime(localtime localtime) { this.localtime = localtime; } } public static void main(string[] args) throws ioexception { myclass myclass = new myclass(); objectmapper mapper = new objectmapper(); string string = mapper.writevalueasstring(myclass); system.out.println(string); myclass myclass2 = mapper.readvalue(string, myclass.class); system.out.println(myclass2.tostring()); } } this code causes own exception thrown
throw new jsonparseexception("start array expected", jp.getcurrentlocation());
by time localtimedeserializer#deserialize called, jackson has moved array token. in other words, within deserialize, jsonparser's current token array token.
you can use validate you're deserializing expect , move on deserialization.
if (jp.getcurrenttoken() != jsontoken.start_array) { throw new jsonparseexception("start array expected", jp.getcurrentlocation()); }
Comments
Post a Comment