简体   繁体   中英

Ignore custom children with Json .Net

i have a json response like this:

{"response_values":[110,{"id":14753,"name":"piter"},{"id":14753,"name":"rabbit"}]}

and i have a simple class

public class Class1
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

and when i trying to convert json to list of the objects with this method:

public T Cast<T>(string json)
{
    var result = default(T);

    var jsonObject = JObject.Parse(json);
    if (jsonObject != null)
    {
        var responseToken = jsonObject["response"];
        result = responseToken.ToObject<T>();
    }

    return result;
}

like this

...

var jsonString = GetJson();
var items = Cast<List<Class1>>();

...

i have an exceiption, because value "110" is integer. How can i skip this value?

You always have this option if you expect the values to ignore to always be at the beginning:

if (jsonObject != null)
{
    var responseToken = parsed["response_values"].SkipWhile(j => j.Type != JTokenType.Object);
    if (responseToken.Count() > 0) result = responseToken.ToObject<T>();
}

You may prefer to use Skip(1) instead of SkipWhile if it's always the first value. Alternatively, you can use Where to ignore or select tokens anywhere in the message.

Of course, you can play around with this approach (changing things) depending on exactly what you expect to be returned in success scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM