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/

相关文章:

c# - WCF,无法找到 ServiceHost 指令中的服务属性值

python - 序列化单个对象?

json - 如何从 Perl 中的 HTTPS 链接获取 JSON?

java - linux下java调用C#mono代码

c# - 使用 PInvoke 时,包含 bool 和 uint 的结构有什么区别?

C# MySQL Blob 字段 - 无法将存储在 blob 中的 zip 文件复制到另一个表

json - Bash循环为mongoimport批量合并文件

json - 如何使用 jq 合并来自 2 个文件的 2 个 JSON 对象?

java - 反序列化 Gson 中的抽象类

c# - 全局资源下本土化的噩梦