在asp.net mvc中为json示例制作模型

时间:2018-12-15 10:20:14

标签: c# asp.net-mvc

请查看此json示例

我想在asp.net mvc中为此json建立模型:

 {
    "MatchStat":{
        {
            "Corner":[10,3], 
            "Offside":[2,1], 
        }
    },

    "FirstTeamArrange":{ 
        "Tactic":"4-4-2",
        "PlayerPos":[0,["PlayerID"],["PlayerID"],["PlayerID"]]
    }
    "SecondTeamArrange":{ 
        "Tactic":"4-4-2",
        "PlayerPos":[0,["PlayerID"],["PlayerID"],["PlayerID"]]
    }

}

[0,[“ PlayerID”],[“ PlayerID”],[“ PlayerID”]]是什么?

它是数组的类型吗?

如何为它写财产?

这是我尝试过的:

  public class MatchModel
{
    public TeamArrange FirstTeamArrange { get; set; }
    public TeamArrange SecondTeamArrange { get; set; }
    public MatchStat Stat { get; set; }

    public MatchModel()
    {

    }


    public class TeamArrange
    {
        public String Tactic { get; set; }

        public string[,,] PlayerPos { get; set; }????????????????????????????

        public TeamArrange()
        {
            Tactic = "";
            PlayerPos=???????????????????????????

        }

    }
    public class MatchStat
    {
        public int[] Corner { get; set; }
        public int[] Offside { get; set; }

        public MatchStat()
        {
            Corner=new int[2];
            Offside=new int[2];
        }
    }


}

您能纠正我的错误吗?

我需要写些什么而不是问号?

1 个答案:

答案 0 :(得分:0)

您需要一个JToken列表才能反序列化PlayerPos密钥数据。

使用下面的类结构正确反序列化json。

class Root
{
    public Dictionary<string, List<int>> MatchStat { get; set; }
    public TeamArrange FirstTeamArrange { get; set; }
    public TeamArrange SecondTeamArrange { get; set; }
}

class TeamArrange
{
    public string Tactic { get; set; }
    public List<JToken> PlayerPos { get; set; }
}

用法:

Root root = JsonConvert.DeserializeObject<Root>(json);

foreach (var item in root.FirstTeamArrange.PlayerPos) //foreach (var item in root.SecondTeamArrange.PlayerPos)
{
    if (item.Type == JTokenType.Integer)
        Console.WriteLine(item.Value<int>());
    else
        if (item.Type == JTokenType.Array)
        {
            var arr = item.ToObject<string[]>();

            foreach (var innerItem in arr)
                Console.WriteLine(innerItem);
        }
}

Console.ReadLine();

输出:

this post