简体   繁体   English

将json嵌套数组解析为c#对象

[英]Parse json nested array into c# object

I´m need to parse a json object into ac# class, my problem is that json object has a nested array and it´s throwing some errors when parsing.我需要将 json 对象解析为 ac# 类,我的问题是 json 对象有一个嵌套数组,并且在解析时会抛出一些错误。

I have tried a couple of options: a) do foreach in the elements of nested array, and add them to a new array b) parsing using json.deserialize我尝试了几个选项:a)在嵌套数组的元素中执行 foreach,并将它们添加到新数组 b)使用 json.deserialize 解析

No success so far至今没有成功

These are my c# classes

public class itemPrediccion
    {
        public string ClavePartido { get; set; }
        public string Ganador { get; set; }
        public bool EsFavorito { get; set; }
    }

    public class Prediccion
    {
        public ObjectId _id { get; set; }
        public string IdUsuario { get; set; }
        public int Jornada { get; set; }
        public IEnumerable<itemPrediccion> PrediccionesJornada { get; set; }
    }

An object of class "Prediccion" would contain a list of "itemPrediccion" “Prediccion”类的对象将包含“itemPrediccion”列表

This is the json object that I want to parse to a "Prediccion" object

{
    "IdUsuario" : "user1", 
    "Jornada" : "1",
    "PrediccionesJornada" : [
        {
            "ClavePartido" : "AP2019J1P1",
            "Ganador": "Morelia",
            "EsFavorito": "false"
        },
        {
            "ClavePartido" : "AP2019J1P2",
            "Ganador": "Chivas",
            "EsFavorito": "false"
        },
        {
            "ClavePartido" : "AP2019J1P3",
            "Ganador": "Atlas",
            "EsFavorito": "true"
        }
    ]
}

This is how I´m trying to deserialize这就是我试图反序列化的方式

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);

Prediccion prediccionUsuario = new Prediccion {
                        IdUsuario = data.IdUsuario,
                        Jornada = data.Jornada,
                        PrediccionesJornada = data.PrediccionesJornada
                    };

Throws this error:抛出这个错误:

Cannot implicitly convert type 'Newtonsoft.Json.Linq.JArray' to 'System.Collections.Generic.IEnumerable'.无法将类型“Newtonsoft.Json.Linq.JArray”隐式转换为“System.Collections.Generic.IEnumerable”。 An explicit conversion exists (are you missing a cast?)存在显式转换(您是否缺少演员表?)

您应该能够使用反序列化器的非动态变体:

var result =JsonConvert.DeserializeObject<Prediccion>(requestBody);

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

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