【问题标题】:JSON parse array C# [closed]JSON解析数组C# [关闭]
【发布时间】:2020-09-27 18:30:12
【问题描述】:

我有以下 json 结构(这是美化的)。我在为以下内容定义类定义时遇到了麻烦(数组中的数组?)。我将如何遍历每个“行”并比较 b->iscritical 例如是否等于 1。

[
  {
    "b": {
      "iscritical": 0,
      "value": "fiber4/2/1"
    },
    "c": {
      "iscritical": 0,
      "value": 1990
    },
    "dd": {
      "iscritical": 0,
      "value": {
        "dname": "Texas",
        "mdomain": "fiber4/2/1",
        "text": "Texas FTTH"
      }
    }
  },
  {
    "b": {
      "iscritical": 0,
      "value": "fiber4/2/2"
    },
    "c": {
      "iscritical": 0,
      "value": 1991
    },
    "dd": {
      "iscritical": 0,
      "value": {
        "dname": "Texas",
        "mdomain": "fiber4/2/2",
        "text": "Texas FTTH"
      }
    }
  }
]

提前谢谢你!

【问题讨论】:

  • 这能回答你的问题吗? How can I parse JSON with C#?
  • 在 Visual Studio 中,您可以将 JSON 粘贴到类中(编辑、选择性粘贴、将 Json 粘贴为类

标签: c# arrays json parsing


【解决方案1】:

你的问题很模糊。您的第一个问题是如何将此 JSON 字符串反序列化为对象。

这是一个较小对象的数组,其中还包含其他对象作为属性。你可以像这样定义你的类:

public class Example
  {
    [JsonProperty("b")]
    public B B { get; set; }

    [JsonProperty("c")]
    public C C { get; set; }

    [JsonProperty("dd")]
    public Dd Dd { get; set; }
  }

  public class B
  {
    [JsonProperty("iscritical")]
    public long Iscritical { get; set; }

    [JsonProperty("value")]
    public string Value { get; set; }
  }

  public class C
  {
    [JsonProperty("iscritical")]
    public long Iscritical { get; set; }

    [JsonProperty("value")]
    public long Value { get; set; }
  }

  public class Dd
  {
    [JsonProperty("iscritical")]
    public long Iscritical { get; set; }

    [JsonProperty("value")]
    public Value Value { get; set; }
  }

  public class Value
  {
    [JsonProperty("dname")]
    public string Dname { get; set; }

    [JsonProperty("mdomain")]
    public string Mdomain { get; set; }

    [JsonProperty("text")]
    public string Text { get; set; }
  }

当您将 JSON 作为字符串时,您可以使用 Newtonsoft.JSON 对其进行反序列化,如下所示:

IEnumerable<Example> values = JsonConvert.DeserializeObject<Example[]>(json);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多