Serialize deserialize anonymous child JSON properties to model

狂风中的少年 提交于 2020-01-02 07:08:30

问题


I have an API I am receiving data from. That API is out of my control on how it is structured, and I need to serialize and deserialize the JSON output to map the data to my model.

Everything works well where JSON is nicely formatted with named properties.

What can you do where there is no named value and there is just an array of ints and strings? like under locations

here is a sample of the JSON:

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

I have models that are like:

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; }
}

and I am mapping using the inbuilt ajax serialization:

 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);

So the ID and all other properties are picked up and mapped but what every I do I can not seem to map the locations.

Many thanks


回答1:


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

job done; you should find that using Json.NET, at least, i.e.

var result = JsonConvert.DeserializeObject<ItemResults>(json);

you get 2 entries in result.Locations; specifically result[103] = "Cambridge"; and result[107] = "London";




回答2:


If you don't mind, you can workaround with dictionary:

class Program
{
    static void Main(string[] args)
    {
        string json =
            "{'id':'2160336','activation_date':'2013-08-01','expiration_date':'2013-08-29','title':'Practice Manager','locations':{'103':'Cambridge','107':'London'}}";
        var deserializeObject = JsonConvert.DeserializeObject<ItemResults>(json);
        Console.WriteLine("{0}:{1}", deserializeObject.Locations.First().Key, deserializeObject.Locations.First().Value);
        Console.ReadKey();
    }
}

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 Dictionary<int, string> Locations { get; set; }
}

you can also use manual parsing, like here: Json.NET (Newtonsoft.Json) - Two 'properties' with same name?




回答3:


This will work:

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 }); } }



回答4:


I propose you the following solution :

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; }
}

After you just have to deserialize your JSON with : JsonConvert.DeserializeObject<ItemResults>(json);



来源:https://stackoverflow.com/questions/18233005/serialize-deserialize-anonymous-child-json-properties-to-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!