简体   繁体   中英

How to deserialize Json String array into separate types using Jackson

I am deserializing some JSON in this format:

"devices": [
  {
    "device": "1",
    "type": "phone",
    "number": "XXX-XXX-0100",
    "name": "",
    "capabilities": [
        "push",
        "sms",
        "phone"
        "mobile_otp"
    ]
  },
  {
    "device": "2",
    "type": "token",
    "name": "0"
  }
]

I'd like to put the "capabilities" into separate object types. For example: Push, Sms, Phone, MobileOtp. I'm using Jackson to deserialize this, and below is what I have come up with, and it works. However, I'd like to find a way to set this up that does not involve having to edit the parent Capability class each time a new subtype is added. Is there a way to do this but still have Jackson correctly parse the JSON? I've tried using template methods or similar to use but nothing seems to work with the Jackson parser. Any ideas?

public abstract class Capability {
    public static final Map<String, Capability> factoryMap = new HashMap<String, Capability>();

    static {
        factoryMap.put("mobile_otp", new Passcode());
        factoryMap.put("phone", new Phone());
        factoryMap.put("push", new Push());
        factoryMap.put("sms", new Sms());
    }

    @JsonCreator
    public static Capability forValue(String value) {
        return factoryMap.get(Strings.nullToEmpty(value).toLowerCase());
    }
}

public class MobileOtp extends Capability {}
public class Phone extends Capability {}
public class Push extends Capability {}
public class Sms extends Capability {}


public class Device { 
    @JsonProperty("capabilities")
    private Collection<Capability> capabilities = new ArrayList<Capability>();

    // other stuff...
}

Instead of simple Map , why not specify an Enum that defines operations, and then type EnumSet<OptionEnum> as property value for capabilities . That gets serialized as JSON array, with string values, like you seem to want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM