c# - 在我的 C# 示例中解释 JSON 结构

标签 c# json

我有这种json结构:

      {
       "Root": {
           "data": [
               {
                   "CardName": "card1",
                   "functions": [
                       {
                           "State": "OPEN",
               "State": "INHERENT"
                       }
                   ]
               },
               {
                   "CardName": "card2",
                   "functions": [
                       {
                           "State": "CLOSED",
               "State": "INHERENT"
                       }
                   ]
               }
           ]
       }
   }

我的 C# 类是:

    [DataContract]
public class Card
{
    [DataMember(Name = "CardName")]
    public string CardName { get; set; }

    [DataMember(Name = "functions")]
    public List<Function> Functions { get; set; }
}

[DataContract]
public class Function
{

    [DataMember(Name = "State")]
    public string State { get; set; }
}

我想解析该结构以获得卡片列表,并且每张卡片都包含一个函数列表。

此刻我正在尝试这个:

        string content = string.Empty;
        using (StreamReader sr = new StreamReader("json"))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                content += line;
            }
        }

   List<Card> dynObj = JsonConvert.DeserializeObject<Card>(content);

但我只得到一个空值列表。你能告诉我问题出在哪里吗?

最佳答案

通过在 Visual Studio 中粘贴 JSON(编辑 > 选择性粘贴 -> 将 JSON 作为类粘贴),它告诉我你的数据的类应该如下所示。

public class Rootobject
{
    public Root Root { get; set; }
}

public class Root
{
    public Datum[] data { get; set; }
}

public class Datum
{
    public string CardName { get; set; }
    public Function[] functions { get; set; }
}

public class Function
{
    public string State { get; set; }
}

关于c# - 在我的 C# 示例中解释 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19244924/

相关文章:

ios - 打印来自 POST 请求的 JSON 数据值的问题

c# - 在单声道下运行时,System.Windows.Forms.Timer 事件根本不会触发

c# - 如何根据选择的 MVC ddl 选项在表中选择一行?

c# - 滚动窗口中的 Gtk Expander : The width of the scrolledwindow doesn't update

javascript - 有条件地在 return 语句中包含 json 字段

json - 如何解码不同数据类型的 JSON 数组?

C# 在桌面图标后面设置窗口

c# - 如何从 TcpClient 读取响应代码

映射表的 SQL 查询直接转换为 JSON

c# - 使用获取的 Json 数据返回 Ajax 成功调用中的部分 View