2016-08-03 15 views
0

ObjectMapperを使用してJSONデータをカスタムオブジェクトに逆シリアル化する際に問題があります。ObjectMapperを使用したJSONからカスタムオブジェクトへの逆シリアル化

構造はこのようなものです:

{ 
    "message": "", 
    "payload": [ 
    { 
     "details": { 
     "id": "7758931", 
     "description": "A description", 
... 

マイコード:

struct MyObject : Mappable 
    { 
     var message : String 
     var payload : [MyDetail]? 

     init(map: Mapper) throws 
     { 
      try message = map.from("message") 
      payload = map.optionalFrom("payload") ?? nil 
     } 
    } 

struct MyDetail : Mappable 
{ 
    var detailId : String 
    var descriptionDetail : String 

    init(map: Mapper) throws 
    { 
     try detailId = map.from("id") 
     try descriptionDetail = map.from("description") 
    } 
} 

解析するための重要な詳細と辞書があるので、明らかにこれは正しくありません...

誰でもどのように私はこれを解析することができる考えがありますか?

+0

struct MyObject : Mappable { var message : String var payload : [MyDetailContainer]? init(map: Mapper) throws { try message = map.from("message") payload = map.optionalFrom("payload") ?? nil } } struct MyDetailContainer : Mappable { var details: MyDetail init(map: Mapper) throws { try details = map.from("details") } } struct MyDetail : Mappable { var detailId : String var descriptionDetail : String init(map: Mapper) throws { try detailId = map.from("id") try descriptionDetail = map.from("description") } } 

は、JSONは次のようにこのように行くと仮定して'details'ネームスペース –

答えて

1

それはこのように、detailsキーの下にネストされていますので、あなたは詳細をラップコンテナオブジェクトを必要とする:あなたが欠場

{ 
    "message": "", 
    "payload": [ 
    { 
     "details": { 
     "id": "7758931", 
     "description": "A description" 
     }, 
    }, 
    { 
     "details": { 
     "id": "7758932", 
     "description": "Description #2" 
... 
+0

ありがとう....例の説明の何らかの理由でnilであれば?すべてのディテールオブジェクトは何も返しません...私はこれをどのように扱うことができますか? – jerrygdm

+1

'descriptionDetail'フィールドをオプションの' String? 'に変更し、それを' try descriptionDetail = map.optionalFrom( "description") 'でマッピングすると、そのトリックを行うべきです – nosyjoe

関連する問題