Reputation: 1112
I'm working on a project that takes an ingested JSON file and outputs a UI based on the file contents. My JSON looks like this:
{
"template" : {
"example" : {
"name" : "Name",
"wigglies" : [
{
"displayname" : "Artifact Spots"
}
],
"othersrc" : [
{
"displayname" : "Other Sources"
}
],
"reward" : "Donation Reward",
"drops" : [
{
"displayname" : "Monster Drops"
}
],
"price0base" : "Base Price",
"edibility" : "Edibility",
"iridium" : "",
"image" : ""
},
"metadata" : {
"author" : "Me",
"version" : "1.0",
"published" : "12/21/2019"
}
},
"content" : {
"categories" : [
{
"category" : "Artifacts",
"subcategories" : [
{
"subcategory" : "Artifacts",
"items" : [
{
"name" : "Amphibian Fossil",
"wigglies" : [
{
"name" : "Forest"
},
{
"name" : "Mountain"
}
],
"othersrc" : [
{
"name" : "Fishing Treasure Chest"
}
],
"price0base" : "150"
},
{
"name" : "Anchor",
"wigglies" : [
{
"name" : "The Beach"
}
],
"othersrc" : [
{
"name" : "Fishing Treasure Chest"
},
{
"name" : "Artifact Trove"
}
],
"price0base" : "100"
}
]
}
]
},
{
"category" : "Equipment",
"subcategories" : [
{
"subcategory" : "Refining",
"items" : [
{
"name" : "Charcoal Kiln"
},
{
"name" : "Crystalarium"
}
]
},
{
"subcategory" : "Artisan",
"items" : [
{
"name" : "Bee House"
},
{
"name" : "Cask"
}
]
}
]
}
]
}
}
What I'm having trouble with is how to return this data in a useful way, while allowing an arbitrary data structure in the array contained by Content.Categories.Category.Subcategories.Subcategory.Items. My sample JSON is not the only structure for that data; it's just one example. So, there could be more nested arrays in there, too.
I know I can access data through something like:
Content.Categories[0].Subcategories[0].Items[0]["name"]
This returns a Json.Linq.Jtoken
though, which isn't super useful. The Items
array is a JObject[]
. I feel like I'm missing something obvious here.
Upvotes: 1
Views: 113
Reputation: 6514
You can use this:
string jsonData = "";
dynamic templates = JsonConvert.DeserializeObject<dynamic>(jsonData);
var name = templates.example.Name; // prints Name
var categories = templates.Content.Categories; // list of categories
// loop through the categories
// or do whatever
This way your code is easier to read and manage.
Upvotes: 0
Reputation: 11364
I believe you are looking for string representation of the JToken. You can get that by using .ToString()
and .ToArray()
for name and items respectively.
JToken name = jsonFeed["content"]["categories"][0]["subcategories"][0]["items"][0]["name"];
string nameString = jsonFeed["content"]["categories"][0]["subcategories"][0]["items"][0]["name"].ToString();
JToken[] itemArray = jsonFeed["content"]["categories"][0]["subcategories"][0]["items"].ToArray();
Upvotes: 1