简体   繁体   English

忽略Json .Net的自定义孩子

[英]Ignore custom children with Json .Net

i have a json response like this: 我有一个像这样的json响应:

{"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: 当我尝试使用此方法将json转换为对象列表时:

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. 我很兴奋,因为值“ 110”是整数。 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. 如果它始终是第一个值,则您可能更喜欢使用Skip(1)而不是SkipWhile Alternatively, you can use Where to ignore or select tokens anywhere in the message. 或者,您可以使用Where位置”忽略或选择消息中任何位置的标记。

Of course, you can play around with this approach (changing things) depending on exactly what you expect to be returned in success scenarios. 当然,您可以根据成功情况下期望返回的结果来尝试这种方法(更改事物)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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