if class extends map , includes fields. e.g last modified date, jackson seems ignore thing not contained property of map.
i have class looks thing following:
import java.io.ioexception; import java.time.offsetdatetime; import java.util.hashmap; import java.util.objects; import com.fasterxml.jackson.databind.objectmapper; public class foo extends hashmap<string, string> { private offsetdatetime lastmodifiedtime; public foo() { super(); lastmodifiedtime = offsetdatetime.now(); } public void setlastmodifiedtime(offsetdatetime newtime) { this.lastmodifiedtime = newtime; } public offsetdatetime getlastmodifiedtime() { return this.lastmodifiedtime; } public static void main(string[] args) throws ioexception { foo f = new foo(); f.put("hello", "world"); objectmapper om = new objectmapper(); om.findandregistermodules(); string result = om.writevalueasstring(f); if(f.equals(om.readvalue(result, foo.class))) { system.out.println("wooo"); } else { system.out.println("booo: " + result); } } @override public boolean equals(object obj) { if (this == obj) { return true; } if (!(obj instanceof foo)) { return false; } if (!super.equals(obj)) { return false; } foo foo = (foo) obj; return objects.equals(getlastmodifiedtime(), foo.getlastmodifiedtime()); } @override public int hashcode() { return objects.hash(super.hashcode(), getlastmodifiedtime()); } } when runs outputs booo: {"hello":"world"} not include last modified date.
i've tried adding @jsoninclude annotations property , getters doesn't cause include field.
what correct way make jackson include field?
it's considered bad practice extend hashmap. instead, should create class has map, , additional field.
this solve problem, have additional advantages:
- you able encapsulate rules (like preventing keys/values added, etc.)
- you able change map implementation if needed (linkedhashmap, synchronized map, concurrent map)
Comments
Post a Comment