将JSON嵌套数组解析为C#对象 [英] Parse json nested array into c# object

查看:74
本文介绍了将JSON嵌套数组解析为C#对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将json对象解析为c#类,我的问题是json对象具有嵌套数组,并且在解析时会引发一些错误.

I´m need to parse a json object into a c# class, my problem is that json object has a nested array and it´s throwing some errors when parsing.

我尝试了几种选择:a)在嵌套数组的元素中进行foreach,并将它们添加到新数组中b)使用json.deserialize进行解析

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

到目前为止没有成功

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

"Prediccion"类的对象将包含"itemPrediccion"的列表

An object of class "Prediccion" would contain a list of "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
                    };

引发此错误:

无法将类型'Newtonsoft.Json.Linq.JArray'隐式转换为'System.Collections.Generic.IEnumerable'.存在显式转换(您是否缺少演员表?)

Cannot implicitly convert type 'Newtonsoft.Json.Linq.JArray' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

推荐答案

您应该能够使用解串器的非动态变体:

You should be able to use the non dynamic variant of the deserializer:

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

这篇关于将JSON嵌套数组解析为C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆