【问题标题】:Parsing JSON file C#解析 JSON 文件 C#
【发布时间】:2012-01-16 22:13:56
【问题描述】:

我有以下要解析为 C# 的 JSON。我试图避免使用外部库,但如果必须,我可以使用它们。现在,我正在使用 JavaScriptSerializer 方法从 JSON 文件中解析另一个 stackoverflow question 的答案,不幸的是,我可以在 Resources 下拥有任意数量的 objectX 项目,它们都有不同的名称。还有其他方法吗?

{
    "FormatVersion" : "2010-09-09",
    "Description" : "My JSON Description",
    "Parameters" : {
        "Product" : {
            "Description" : "Product name",
            "Type" : "String",
            "Default" : "cs42"
        },
        "DifferentObjectSize" : {
            "Description" : "DifferentObjectSize",
            "Type" : "String",
            "Default" : "large"
        },
        "ObjectSize" : {
            "Description" : "Worker size",
            "Type" : "String",
            "Default" : "medium"
        }
     },

    "Resources" : {

        "differentobject" : {
          "Type" : "MyType",
          "Properties" : {
            "InstanceType" : { "Ref" : "DifferentObjectSize" }
          }
        },

        "object1" : {
          "Type" : "MyType",
          "Properties" : {
            "InstanceType" : { "Ref" : "ObjectSize" }
          }
        },

        "object2" : {
          "Type" : "MyType",
          "Properties" : {
            "InstanceType" : { "Ref" : "ObjectSize" }
          }
        },

        "object3" : {
          "Type" : "MyType",
          "Properties" : {
            "InstanceType" : { "Ref" : "ObjectSize" }
          }
        },

        "object4" : {
          "Type" : "MyType",
          "Properties" : {
            "InstanceType" : { "Ref" : "ObjectSize" }
          }
        },

    }
}

【问题讨论】:

  • 您的目标是什么版本的 .NET?
  • 好吧,我推出了自己的。 JSON 不是很复杂,大概一天左右就能搞定。

标签: c# json parsing serialization


【解决方案1】:

如果你想使用Json.Net,你可以如下解析你的输入字符串

JObject myObj = (JObject)JsonConvert.DeserializeObject(jsonString);
foreach(var resource in myObj["Resources"])
{
    var props = resource.Children<JObject>().First();
    Console.WriteLine(props["Type"] + " " + props["Properties"]["InstanceType"]["Ref"]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2021-02-01
    • 2017-08-15
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多