如何根据json中的属性编写jackson反序列化器

时间:2016-02-17 11:50:26

标签: java json jackson deserialization json-deserialization

我想在类Type上编写json反序列化器,这样当基于名称从给定的json反序列化Type时,它会根据一些工厂方法将值(接口类型为)映射到其当前实现,该方法根据名称返回正确的类名,并在没有任何明确的反序列化的情况下填充剩余的类,并且不使用new创建TigerBeing或HumanBeing的对象。

我尝试使用@jsonCreator但是我必须使用new初始化整个HumanBeing或TigerBeing并在构造函数中传递所有json。我需要自动映射进一步用作进一步pojo的类型可能非常复杂。

{type:[{
    "name": "Human",
    "value": { 
        "height":6,
        "weight":100,
        "languages":["spanish","english"]
    }
 },
{
"name":"Tiger",
"value":{
    "extinct":1,
    "found":["Asia", "America", "Europe", "Africa"]
}
}
]}

I have:

public class Type {
    String name;
    Being value;
}

public interface Being {
}

public class TigerBeing implements Being { 
    Integer extinct;
    String[] found;
}

public class HumanBeing implement Being {
    Integer height;
    Integer weight;
    String[] languages;
}

1 个答案:

答案 0 :(得分:1)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
   self.window = UIWindow(frame: UIScreen.main.bounds)
   let storyboard = UIStoryboard(name: "Main", bundle: nil)
   let viewController = storyboard.instantiateViewController(withIdentifier: "Identifier")
   let navigationController = UINavigationController(rootViewController: viewController)
   self.window?.rootViewController = navigationController
   self.window?.makeKeyAndVisible()

   return true
}

通过这种方式,我能够解决上述问题。