开发者

Use different bean class in Jackson JSON based on variable?

I have JSON like the following:

[{
  'kind':'1',
  'value1': 'foo',
  'value2': 'bar',
  ...
},
{
  'kind':'2',开发者_运维问答
  'value1': 'foo',
  'value2': 'bar',
  ...
}
..]

Basically a list of objects with the same variables. In my code, I'd like to create an ArrayList of some class A, which would contain these objects. However, I'd like each object to be of subclass One or Two, depending on the 'kind' value.

How can I accomplish this?

Thanks!


This is what Jackson calls "polymorphic type handling". There's a good explanation of how to do this here. You need to tell Jackson to put the class name into the JSON when you serialize it, and use that class name when you deserialize it. This is done via annotation:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, 
              include=JsonTypeInfo.As.PROPERTY, property="kind")

[Source: @StaxMan (below).]

If you don't have control over the JSON format, you can use Jackson to deserialize it into some common intermediate object and then write code that creates the desired subclass object from it. Alternatively, use the json.org library to deserialize the JSON string into an org.json.JSONObject, and then write code to construct your desired objects based on the JSONObject's properties.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜