3

TL; DR

基本的に、私の問題は、ラッパーオブジェクトのリストがあることです

{"stuff": [
  {"foobar" : {someObjectOfTypeA}},
  {"barfoo" : {someObjectOfTypeB}},
  {"foobar" : {someObjectOfTypeA}}
]}

また、someObjectOfTypeXのタイプは、キー「foobar」または「barfoo」の値によって異なります。どうすればこれを逆シリアル化できますか?(今のところ)シリアル化は問題ではありません。


ロングバージョン

私は次の問題を解決するのに十分なジャクソンを知りません。試しましたが、行き詰まりました。

解析したいjson構造は次のようになります。

{
  "id": "foobar",
  "responses": [
    {
      "responseType1": {
        "code": 0,
        "foo": "bar"
      }
    },
    {
      "responseType2": {
        "code": 1,
        "bar": {"foo": ...}
      }
    },
    {
      "responseType1": {
        "code": 1,
        "foo": "foobar"
      }
    }
  ]
}

jacksonsの完全なデータバインディングを使用して逆シリアル化しようとしました。私のpojoは次のとおりです。

// pseudocode

// the outermost object
@JsonCreator
ServiceResponse(
  @JsonProperty("id") String id, 
  @JsonProperty("responses") ArrayList<ResponseWrapper> responses)

// every response has a wrapper. the wrapper is an object with just one key and one value. the value is an object of a certain class (ResponseTypeX extends AResponse), and the exact ResponseType is identified by the key (the key isn't the class name though). 
@JsonCreator
ResponseWrapper(AResponse keyDependsOnTypeOfAResponse ???)

// base class for all responseTypeX classes
// all subclasses of AResponse have a code and a complex payload object
@JsonCreator
AResponse (
  @JsonProperty("code") int code)

// one response type
// here, the payload is just a string, in reality it's a deep structure, so i dont want to parse this manually
@JsonCreator
ResponseType1 extends AResponse (
  @JsonProperty("code") int code,
  @JsonProperty("foo") String foo)

// one response type
@JsonCreator
ResponseType2 extends AResponse (
  @JsonProperty("code") int code,
  @JsonProperty("bar") SomeOtherObject foo)

ご覧のとおり、responsesはラッパーオブジェクトの配列です。ラッパーオブジェクトの「ペイロード」クラスはキーによって識別されます(ただし、キーはクラス名と1:1で一致しません)。私のResponseTypeXは限られており、約20個あるので、手動でkey:valueタイプの識別を行う必要がある場合は、満足しています。

しかし、WrapperResponseオブジェクトの手動デシリアライザーを作成し、完全なデータバインディングを使用してその子のデシリアライズを続行することは可能ですか?もしそうなら、どのように?


可能なすべてのResponseTypeをプロパティとしてWrapperに受け入れさせようとしました。これにより、「未設定」のResponseTypeが無効になることを期待しています。

@JsonCreator
ResponseWrapper(
  @JsonProperty("responseKey1") ResponseType1 response1,
  @JsonProperty("responseKey2") ResponseType2 response2,
  @JsonProperty("responseKey3") ResponseType3 response3,
  ...)

しかし、これは失敗しました。おそらく、すべてのResponseTypeがAResponseのサブクラスであるため、jacksonが混乱するためです。

4

1 に答える 1

3

いくつかのカスタム逆シリアル化処理が必要です。2011年5月25日の古いブログ投稿の6番目の例のように、ソリューションにfoobar / barfoo-to-typeエントリの単純なレジストリ(マップ)を含めることをお勧めします。完全な例」

于 2012-12-08T22:40:30.723 に答える