3

First of all I have checked all old questions and found this one useful: Reading dynamic attributes of json into .net C# but wasn't so useful in my case, I'm missing something not sure what is it!

I'm trying to read dynamic JSON with nested dynamic attributes, here is the JSON:

{"data":{"cart":{"seats":{"3B00535EF2414332":{"212":{"6":["22","21"]}}}}}}

Please keep in mind that 3B00535EF2414332, 212 and 6 are dynamic each time I get this JSON. In C#, I don't know how should I set the attributes as I need to provide a class with properties with exact the same name of the object to deserialize this object. I though about parsing it to dynamic object in C# and try to call it, but still can't as the only known value for me each time is 3B00535EF2414332 but other 2 dynamic properties are not known to me, I need to retrieve them.

I though about the dictionary way, but I couldn't create it right. Actually, I didn't understand it right.

Thanks for your time.

4
  • what values are you trying to extract here? (22 and 21)? Commented Feb 8, 2018 at 17:14
  • Nope, I need to get 3B00535EF2414332 , 212, 6, 22, 21, gonna test your solution, thanks. Commented Feb 8, 2018 at 17:40
  • are they always in this structure (int[] under 3 layers from data.cart.seats)? Commented Feb 8, 2018 at 17:44
  • Yes, they are always like that static, but after that went dynamic..! Commented Feb 8, 2018 at 17:52

1 Answer 1

4

You can try this:

var results = JObject.Parse(json)
    ["data"]["cart"]["seats"]
    .Children<JProperty>().First().Value
    .Children<JProperty>().First().Value
    .Children<JProperty>().First().Value
    .ToObject<int[]>();

EDIT: you can also use this to retrieve the values along with the path names:

var seats = JObject.Parse(json)["data"]["cart"]["seats"].Children<JProperty>();
var unknown0 = seats.First();
var unknown1 = unknown0.Value.Children<JProperty>().First();
var unknown2 = unknown1.Value.Children<JProperty>().First();

// unknown0.Name -> 3B00535EF2414332
// unknown1.Name -> 212
// unknown2.Name -> 6;
// unknown2.Value.ToObject<int[]>() -> [22,21]
Sign up to request clarification or add additional context in comments.

7 Comments

Out of curiosity, what happens if there aren't any children, after the first .Children...?
You are awesome! Thanks a lot. Got all data I want with this!
@MeghanArmes, I think it gonna return Null or even throw exception, that's why you may use FirstOrDefault, so you can handle if it's with null!
@AhmedÕşşama that makes sense. :) Good call!
@MeghanArmes For the record, you will get a InvalidOperationException "Sequence contains no elements"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.