2016-08-30 18 views
0

私は、Json.net APIのJsonConvert.PopulateObjectを使用しています。これは、まず2つのパラメータ、つまりjson文字列を受け取り、次に2つ目は、入力する実際のオブジェクトです。Json.netでのプロパティのカスタム逆シリアル化

私が記入するオブジェクトの構造は

internal class Customer 
{ 

    public Customer() 
    { 
     this.CustomerAddress = new Address(); 
    } 
    public string Name { get; set; } 

    public Address CustomerAddress { get; set; } 
} 

public class Address 
{ 
    public string State { get; set; } 
    public string City { get; set; } 

    public string ZipCode { get; set; } 
} 

私のJSON文字列が

{ 
    "Name":"Jack", 
    "State":"ABC", 
    "City":"XX", 
    "ZipCode":"098" 
} 

Nameプロパティが、それはJSON文字列に存在するbecuase満たさが、CustomerAddressがありますされています人口が増えることはありません。 json.netのライブラリに、CustomerAddress.Cityをjson文字列のCityプロパティから読み込む方法はありますか?

答えて

1

ダイレクトに - いいえ。

しかし、これを達成することは可能です。

class Customer 
{ 
    public string Name { get; set; } 
    public Address CustomerAddress { get; set; } = new Address(); // initial value 

    // private property used to get value from json 
    // attribute is needed to use not-matching names (e.g. if Customer already have City) 
    [JsonProperty(nameof(Address.City))] 
    string _city 
    { 
     set { CustomerAddress.City = value; } 
    } 

    // ... same for other properties of Address 
} 

他の可能性:ここに(あなたはJSONを変更することはできませんと仮定)の試みです

  • Addressオブジェクトを格納するための変更JSON形式は、
  • カスタムシリアル化(バインダーを使用してタイプをシリアル化し、必要に応じて変換するなど)。
  • ...(もっとする必要があります)
関連する問題