0

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

    }
}
Community
  • 1
  • 1
John Neville
  • 424
  • 1
  • 5
  • 17

1 Answers1

4

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"]);
}
L.B
  • 114,136
  • 19
  • 178
  • 224