JSON.net - field is either string or List

后端 未结 2 1053
无人及你
无人及你 2020-12-03 20:47

I have a situation where the JSON returned from a REST-service returns a list of Movie-objects, all specced out with a ton of information. A couple

2条回答
  •  情歌与酒
    2020-12-03 21:30

    You won't be able to serialise directly to an object, but you can do so manually without too much effort. JSON.Net contains LINQ to JSON. First define a method that will always return a list of type T even if the underlying JSON is not an array:

    public List getSingleOrArray(JToken token)
    {
        if (token.HasValues)
        {
            return token.Select(m => m.ToObject()).ToList();
        }
        else
        {
            return new List { token.ToObject() };
        }
    }
    

    Sample usage:

    JObject m1 = JObject.Parse(@"{
    ""title"": ""Movie title"",
    ""images"": [
        ""http://www.url.com/img_0.jpg"",
        ""http://www.url.com/img_1.jpg""
    ],
    ""actors"": [
        ""Steven Berkoff"",
        ""Julie Cox""
    ],
    ""directors"": ""Simon Aeby""
    }");
    
    JObject m2 = JObject.Parse(@"{
    ""title"": ""Another movie"",
    ""images"": ""http://www.url.com/img_1.jpg"",
    ""actors"": ""actor 1"",
    ""directors"": [
        ""Justin Bieber"",
        ""Justin Timberlake""
    ]
    }");
    
    IList m1_directors = getSingleOrArray(m1["directors"]);
    IList m2_directors = getSingleOrArray(m2["directors"]);
    

    m1_directory is a list with a single element, m2_directors is a list with two elements.

提交回复
热议问题