1

I want to parse JSON with an undefined structure (any possible correct JSON) with Newtonsoft.Json using C# in Visual Studio 2015.

First, I read and parse JSON into a JToken:

...
var jsonData = ReadTextFromFile(filename);
var root = JToken.Parse(jsonData);
...

Now, I need to iterate through the JToken to construct my own tree JsonTree consisting of JsonTreeNode with additional info about every node.

Here is my JsonTreeNode class:

public class JsonTreeNode
{
    public JsonTreeNode()
    { }

    public JsonTreeNode(string name, string value, bool isArray, List<JsonTreeNode> children, JsonTreeNode parent, SomeAdditionalInfo info)
    {
        Name = name;
        Value = value;
        IsArray = isArray;
        Children = children;
        ParentTreeNode = parent;
        AdditionalInfo = info;
    }
    public string Name { get; set; }
    public string Value { get; set; }
    public bool IsArray { get; set; }
    public JsonTreeNode ParentTreeNode { get; set; }
    public List<JsonTreeNode> Children { get; set; }
    public SomeAdditionalInfo AdditionalInfo { get; set; }
}

Function to convert:

private static void ParseJsonToNode(JToken jsonToken, JsonTreeNode treeNode){...}

I don't know how convert each JToken to SomethingElse, so that I can get the Name and Value.

Here is a JSON file which shows the problem:

{
    "name": "Jack",
    "age": 29
}

When I parse it through foreach or recursively, the JToken has:

JToken(name):
-Type: Property
-Name: name
-Value: (Has no value)
-Children: 1
    JToken(Jack)
    -Type: String
    -Name (Has no name)
    -Value: "Jack"
    -Children: 0
JToken(age)
-Type: Property
-Name: age
-Value: (Has no value)
-Children: 1
    JToken(29)
    -Type: Integer
    -Name (Has no name)
    -Value: 29
    -Children: 0

But I don't need two JTokens for one value. I don't know how to composite them in the best way!

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
murzagurskiy
  • 1,273
  • 1
  • 20
  • 44
  • Check whether it's a `JObject`, `JArray`, or other type. – SLaks Dec 18 '16 at 15:11
  • @SLaks add example – murzagurskiy Dec 18 '16 at 15:22
  • You will have to manually deal with the fact that `JObject` values have an additional level of nesting not present in `JArray` members. See (How to recursively populate a TreeView with JSON data)[http://stackoverflow.com/a/39675191/3744182] for an example of how it might be done. – dbc Dec 19 '16 at 22:33

0 Answers0