C
C#3mo ago
Alex

How to deserialize only child object

I have a json structure and I need only studiableItems data. How can I deserialize only it without creating classes for parent items?
{
"props":{
"pageProps": {
"dehydratedReduxStateKey": {
"studyModesCommon": {
"studiableData": {
"studiableItems": [
{""item1"": ""data1""},
{""item2"": ""data2""},
{""item3"": ""data3""}
]
}
}
}
}
}
}
{
"props":{
"pageProps": {
"dehydratedReduxStateKey": {
"studyModesCommon": {
"studiableData": {
"studiableItems": [
{""item1"": ""data1""},
{""item2"": ""data2""},
{""item3"": ""data3""}
]
}
}
}
}
}
}
7 Replies
ThatDaniel
ThatDaniel3mo ago
var json = @"{
""props"":{
""pageProps"": {
""dehydratedReduxStateKey"": {
""studyModesCommon"": {
""studiableData"": {
""studiableItems"": [
{""item1"": ""data1""},
{""item2"": ""data2""},
{""item3"": ""data3""}
]
}
}
}
}
}
}";

var jsonNode = JsonNode.Parse(json);
var studiableItems = jsonNode["props"]["pageProps"]["dehydratedReduxStateKey"]["studyModesCommon"]["studiableData"]["studiableItems"];

Console.WriteLine(studiableItems.ToJsonString());
var json = @"{
""props"":{
""pageProps"": {
""dehydratedReduxStateKey"": {
""studyModesCommon"": {
""studiableData"": {
""studiableItems"": [
{""item1"": ""data1""},
{""item2"": ""data2""},
{""item3"": ""data3""}
]
}
}
}
}
}
}";

var jsonNode = JsonNode.Parse(json);
var studiableItems = jsonNode["props"]["pageProps"]["dehydratedReduxStateKey"]["studyModesCommon"]["studiableData"]["studiableItems"];

Console.WriteLine(studiableItems.ToJsonString());
ThatDaniel
ThatDaniel3mo ago
C# Online Compiler | .NET Fiddle
Test your C# code online with .NET Fiddle code editor.
ThatDaniel
ThatDaniel3mo ago
Using System.Text.Json.Nodes or you can use another json package but I like this syntax
Pobiega
Pobiega3mo ago
or use records for the entire structure and deserialize
ThatDaniel
ThatDaniel3mo ago
they didnt want to do that
Pobiega
Pobiega3mo ago
because stringly typed is... still typed. I dont see how jsonNode["props"]["pageProps"]["dehydratedReduxStateKey"]["studyModesCommon"]["studiableData"]["studiableItems"]; is better
Alex
Alex3mo ago
Thank you