Parsing dynamic JSON string to string in C # using JSON.NET

This is my first little project in C # and JSON. I am asked to parse a JSON file as follows: I am trying to create a Windows form whose body will contain the contents of a JSON string in the following format:

Name of the object
(Label) name of the attribute of the object - (TextBox) editable value
(Label) name of the attribute of the object - (TextBox) editable value
...

      

I have approximately 35 attributes per object in json file and 8 objects. There are about 50 different attributes in total. I searched for JSON - C # - JSON.NET and read over 15 questions and answers. The answers provided valuable information for beginners like me, but I could not relate the answers to my situation. Here are the reasons:

  • Some answers have converted json string to C # objects. Since I need the "names" of the attributes of the objects, this option didn't hit me as a solution. I don't know how to get the name of the variable in the source code and use it in the window form.
  • Some answers have converted the json string to data structure <Dictionary>

    . I don't fully understand dictionaries and their properties, but by definition, I think dictionaries map 2 values ​​to each other. In my case, 3-5 different objects can have the same attribute, so there will be multiple values ​​for one attribute.

Also, the example I saw was:

var dict = new JavaScriptSerializer().Deserialize<Dictionary<string,object>>(json); var postalCode = dict["postalcode"];

Since I have about 50 attributes, using this approach is not an option for me: using the field names one after the other, as it did in this example ("postcode" was one of the attributes in the json object example in the linked question).

At first glance, I thought I could parse it myself using string manipulation. But I want to use the beautiful JSON.NET library. I'm kind of stuck here with no idea how to get the attribute name of a json object and use it and its value in a window form. I have ideas, but I have no idea how to implement them.

I can parse a json string that contains 8 objects into an array of objects, each object containing arrays of 2D strings for their name and attribute value. Then I will convert the string to float while editing the value. I need them as strings because I want to use them in a window form. This is my decision. How can I proceed?

+2


source to share


2 answers


Since you have a dynamic json string, I would recommend parsing the string as JObject

. This gives you the most flexibility when handling a tree of JSON objects:

var parseTree = JsonConvert.DeserializeObject<JObject>("{ a: 2, b: \"a string\", c: 1.75 }");
foreach (var prop in parseTree.Properties()) {
    Console.WriteLine(prop.Name + ": " + prop.Value.ToObject<object>());
}

      

Another example JObject

:

var parsed = JsonConvert.DeserializeObject<JObject>("{\"name\":{\"a\":2, \"b\":\"a string\", \"c\":3 } }");
foreach (var property in parsed.Properties()) {
    Console.WriteLine(property.Name);
    foreach (var innerProperty in ((JObject)property.Value).Properties()) {
        Console.WriteLine("\t{0}: {1}", innerProperty.Name, innerProperty.Value.ToObject<object>());
    }
}

      



If you know you are dealing with a JSON array, you can instead parse how JArray

and then look at each one JObject

in the array:

var properties = JsonConvert.DeserializeObject<JArray>("[{a:1}, {b:2, c:3 }]")
    .SelectMany(o => ((JObject)o).Properties())
    .ToArray();
foreach (var prop in properties) {
    Console.WriteLine(prop.Name + ": " + prop.Value.ToObject<object>());
}

      

For more flexibility, you can parse how JToken

.

+6


source


For such dynamic JSON, you might consider something less cumbersome than JSON.NET like SimpleJson ( https://github.com/facebook-csharp-sdk/simple-json ) It's just a .cs file that you copy / paste into your project or install via NuGet.

It supports "dynamic" and is extremely easy to use.

For example, if you have JSON like:

{
  "inputs" : ["a", "b", "c"],
  "outputs" : ["c", "d", "e"]
}

      

You can parse it:

dynamic sys = SimpleJson.DeserializeObject(jsonString);

      



And then we get everything at once:

foreach(var attr in sys) {
  foreach( var name in attr ) {
      Console.WriteLine("In {0} with name: {1}", attr, name);
  }
}

      

You can of course also access by name or index:

Console.WriteLine(sys["inputs"][0]);

      

which will print 'a'.

+2


source







All Articles