3

データを受信して​​いる API があります。その API は、その構造を制御することはできず、JSON 出力をシリアル化および逆シリアル化して、データをモデルにマップする必要があります。

JSONが名前付きプロパティで適切にフォーマットされている場合、すべてがうまく機能します。

名前付きの値がなく、int と文字列の配列だけがある場合に何ができますか? 場所の下のように

JSON のサンプルを次に示します。

{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":{"103":"Cambridge","107":"London"}}

次のようなモデルがあります。

public class ItemResults
{
    public int Id { get; set; }

    public DateTime Activation_Date { get; set; }

    public DateTime Expiration_Date{ get; set; } 

    public string Title { get; set; }

    public Location Locations { get; set; }
}

public class Location
{
    public int Id { get; set; }

    public string value { get; set; }
}

組み込みの ajax シリアライゼーションを使用してマッピングしています。

 protected T MapRawApiResponseTo<T>( string response )
    {
        if ( string.IsNullOrEmpty( response ) )
        {
            return default( T );
        }

        var serialize = new JavaScriptSerializer();

        return serialize.Deserialize<T>( response );
    }

var results = MapRawApiResponseTo<ItemResults>(rawApiResponse);

そのため、ID と他のすべてのプロパティが取得され、マップされますが、何をしても場所をマップできないようです。

どうもありがとう

4

4 に答える 4

1

これはうまくいきます:

public Dictionary<string, string> Locations { get; set; }

public IEnumerable<Location> LocationObjects { get { return Locations
     .Select(x => new Location { Id = int.Parse(x.Key), value = x.Value }); } }
于 2013-08-14T13:37:18.713 に答える
1

次の解決策を提案します。

public class ItemResults
{
    public int Id { get; set; }

    public DateTime Activation_Date { get; set; }

    public DateTime Expiration_Date { get; set; }

    public string Title { get; set; }

    [JsonProperty("locations")]
    public JObject JsonLocations { get; set; }

    [JsonIgnore]
    public List<Location> Locations { get; set; }

    [OnDeserialized]
    public void OnDeserializedMethod(StreamingContext context)
    {
        this.Locations = new List<Location>();
        foreach (KeyValuePair<string, JToken> item in this.JsonLocations)
        {
            this.Locations.Add(new Location() { Id = int.Parse(item.Key), value = item.Value.ToString() });
        }
    }
}

public class Location
{
    public int Id { get; set; }

    public string value { get; set; }
}

JSONを次のように逆シリアル化する必要があるだけです。JsonConvert.DeserializeObject<ItemResults>(json);

于 2013-08-14T13:41:03.257 に答える