I have a JSON structure that I would like to manually parse to a POCO object using JSON.NET.
我有一个JSON结构,我想使用JSON.NET手动解析到POCO对象。
The JSON structure is a bunch of nested dictionaries... The root dictionary contains categories, the next level contains products within those categories and the last level contains versions of those products.
JSON结构是一堆嵌套字典……根字典包含类别,下一个级别包含这些类别中的产品,最后一个级别包含这些产品的版本。
{
"category-1": {
"product-1": {
"product-version-1": {
"id":1,
...
}
}
},
"category-2": {
"product-2": {
"product-version-2": {
"id":2,
...
}
},
"product-3": {
"product-version-3": {
"id":3,
...
}
}
}
}
I would like to parse this structure, keeping in mind the keys of all the dictionaries are not known to me ahead of time.
我想要解析这个结构,记住所有的字典的键在我之前都不知道。
This was the code that I had written (I was going to convert to LINQ once it worked...) - I expected this to work with a couple of nested loops but clearly JTokens and JObjects don't work the way I thought... Id is always null.
这是我所编写的代码(我打算在它运行后将其转换为LINQ…)——我希望它可以与一些嵌套循环一起工作,但是很明显jtoken和JObjects不能像我想的那样工作……Id总是空的。
var productsJObject = JObject.Parse(result.Content.ReadAsStringAsync().Result);
foreach (var category in productsJObject)
{
foreach (var product in category.Value)
{
foreach (var version in product)
{
var poco = new Poco
{
Id = version.SelectToken("id").ToString()
};
}
}
}
So my question, how can I iterate over nested dictionaries using JSON.Net?
我的问题是,如何使用JSON.Net遍历嵌套字典?
1 个解决方案
#1
6
Found this question trying to figure out how to parse JSON.NET in C#. Hopefully my answer will help someone else...
找到了这个问题,试图找出如何解析JSON。净在c#中。希望我的回答能对其他人有所帮助……
I wrote this code to help me parse a random JSON object and analyze the structure. It's somewhat rough and probably doesn't handle all scenarios, but it does the trick. Right now its just storing locations in a dictionary, but it should be pretty easy to see what its doing and modify it to do what you want:
我编写这段代码是为了帮助我解析一个随机的JSON对象并分析其结构。它有点粗糙,可能不能处理所有的场景,但它确实能解决问题。现在它只是在字典中存储位置,但它应该很容易看到它在做什么,并修改它以实现您想要的:
static void Main(string[] args)
{
Dictionary<string, string> nodes = new Dictionary<string, string>();
// put your JSON object here
JObject rootObject = JObject.Parse("{\"world\": {\"hello\": \"woo\", \"foo\": \"bar\", \"arr\": [\"one\", \"two\"]}}");
ParseJson(rootObject, nodes);
// nodes dictionary contains xpath-like node locations
Debug.WriteLine("");
Debug.WriteLine("JSON:");
foreach (string key in nodes.Keys)
{
Debug.WriteLine(key + " = " + nodes[key]);
}
}
/// <summary>
/// Parse a JSON object and return it as a dictionary of strings with keys showing the heirarchy.
/// </summary>
/// <param name="token"></param>
/// <param name="nodes"></param>
/// <param name="parentLocation"></param>
/// <returns></returns>
public static bool ParseJson(JToken token, Dictionary<string, string> nodes, string parentLocation = "")
{
if (token.HasValues)
{
foreach (JToken child in token.Children())
{
if (token.Type == JTokenType.Property)
parentLocation += "/" + ((JProperty)token).Name;
ParseJson(child, nodes, parentLocation);
}
// we are done parsing and this is a parent node
return true;
}
else
{
// leaf of the tree
if (nodes.ContainsKey(parentLocation))
{
// this was an array
nodes[parentLocation] += "|" + token.ToString();
}
else
{
// this was a single property
nodes.Add(parentLocation, token.ToString());
}
return false;
}
}
#1
6
Found this question trying to figure out how to parse JSON.NET in C#. Hopefully my answer will help someone else...
找到了这个问题,试图找出如何解析JSON。净在c#中。希望我的回答能对其他人有所帮助……
I wrote this code to help me parse a random JSON object and analyze the structure. It's somewhat rough and probably doesn't handle all scenarios, but it does the trick. Right now its just storing locations in a dictionary, but it should be pretty easy to see what its doing and modify it to do what you want:
我编写这段代码是为了帮助我解析一个随机的JSON对象并分析其结构。它有点粗糙,可能不能处理所有的场景,但它确实能解决问题。现在它只是在字典中存储位置,但它应该很容易看到它在做什么,并修改它以实现您想要的:
static void Main(string[] args)
{
Dictionary<string, string> nodes = new Dictionary<string, string>();
// put your JSON object here
JObject rootObject = JObject.Parse("{\"world\": {\"hello\": \"woo\", \"foo\": \"bar\", \"arr\": [\"one\", \"two\"]}}");
ParseJson(rootObject, nodes);
// nodes dictionary contains xpath-like node locations
Debug.WriteLine("");
Debug.WriteLine("JSON:");
foreach (string key in nodes.Keys)
{
Debug.WriteLine(key + " = " + nodes[key]);
}
}
/// <summary>
/// Parse a JSON object and return it as a dictionary of strings with keys showing the heirarchy.
/// </summary>
/// <param name="token"></param>
/// <param name="nodes"></param>
/// <param name="parentLocation"></param>
/// <returns></returns>
public static bool ParseJson(JToken token, Dictionary<string, string> nodes, string parentLocation = "")
{
if (token.HasValues)
{
foreach (JToken child in token.Children())
{
if (token.Type == JTokenType.Property)
parentLocation += "/" + ((JProperty)token).Name;
ParseJson(child, nodes, parentLocation);
}
// we are done parsing and this is a parent node
return true;
}
else
{
// leaf of the tree
if (nodes.ContainsKey(parentLocation))
{
// this was an array
nodes[parentLocation] += "|" + token.ToString();
}
else
{
// this was a single property
nodes.Add(parentLocation, token.ToString());
}
return false;
}
}