解析JSON文件C# [英] Parsing JSON file C#

查看:105
本文介绍了解析JSON文件C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下要解析为C#的JSON.我试图避免使用外部库,但是如果需要的话,我可以使用它们.现在,我正在使用JavaScriptSerializer方法,根据另一个 stackoverflow问题不幸的是,我在参考资料下可以有任意数量的objectX项,并且它们都有不同的名称.还有另一种方法吗?

I have the following JSON that I want to parse into C#. I am trying to avoid outside libraries but if I have to I can use them. Right now I am using the JavaScriptSerializer method of parsing from a JSON file following the answer on another stackoverflow question Unfortunately I can have any number of the objectX items under Resources and they all have different names. Is there another way of doing this?

{
    "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" }
          }
        },

    }
}

推荐答案

如果您考虑使用 Json.Net 您可以按如下方式解析您的输入字符串

If you think to use Json.Net you can parse your input string as below

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"]);
}

这篇关于解析JSON文件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆