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

    }
}
2
  • What version of .NET are you targeting? Commented Jan 16, 2012 at 22:15
  • Well, I rolled out my own. JSON isn't very complicated, you can probably get it done in a day or so. Commented Jan 16, 2012 at 22:17

1 Answer 1

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"]);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.