Jack
Jack

Reputation: 16724

How do I serialize this kind of json?

I have a JSON string (not created by me) that has identifiers not valid in C#, like this:

"OBSBasic.SelectScene": [],
"libobs.hide_scene_item.Captura de Janela": [],

and

 "push-to-mute-delay": 0,

and son on...

here's the full json.

My question is:

How can I convert that JSON into a kind of Dictionary so that I can like that:

dic["sources"][0]["settings"]["window"] = "XXXX";

I don't know for sure all the possible properties names that JSON file can have, so I'd like to really convert it into an array-baseed approach so that I can access it from a key rather a property name from my object used to deserialized that would eventually fail if a new property was generated, for example.

I tried without success something like this:

dynamic data = JsonConvert.DeserializeObject(jsonstr);
data.sources.settings.window = "xxxx";

That resulted in a runtime exception:

Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in Microsoft.CSharp.dll Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in System.Core.dll

I have no code else to show bcause I'm stuck at how the dictionary would look like to be passed in DeserializeObject<T>() method. I'd like to serialized that JSON object back to string later.

Upvotes: 1

Views: 93

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129657

If you parse your JSON into a JToken you can use the syntax you want to access your data:

    JToken dic = JToken.Parse(json);

    Console.WriteLine(dic["sources"][1]["settings"]["window"]);

Fiddle: https://dotnetfiddle.net/jZrI44

Upvotes: 1

Related Questions