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!