Parsing Json into a dynamic C # object with a dynamic key

I am trying to parse this Google calendar answer that I get from my Rest API using C #, but I seem to get stuck all the time. [edited] Update, the @ symbol does not interfere with drilling, I checked by replacing @ with _at_ . See screenshot of Quick Watch: enter image description here

I am sure that I am addressing this incorrectly ...

Here's jsonString I'm trying to parse:

 { "kind": "calendar#freeBusy", "timeMin": "2015-06-12T14:00:00.000Z", "timeMax": "2015-06-14T14:00:00.000Z", "calendars": { " joe@bobs.com ": { "busy": [ { "start": "2015-06-13T18:30:00Z", "end": "2015-06-13T19:30:00Z" }, { "start": "2015-06-13T20:30:00Z", "end": "2015-06-13T21:30:00Z" }, { "start": "2015-06-13T23:00:00Z", "end": "2015-06-14T00:00:00Z" } ] } } } 

I tried using:

 dynamic myObj = Json.Decode(jsonString); 

and

 var myObj = JsonConvert.DeserializeObject(jsonString); 

but I can’t figure out how to enter the joe@bobs.com key (which is dynamic based on what I am sending) to cycle through all busy times.

Ideas?

enter image description here

+6
source share
2 answers

You can access it using the row indexer:

 var myObj = JsonConvert.DeserializeObject<dynamic>(jsonString); Console.WriteLine(myObj.calendars[" joe@bobs.com "]); 
+3
source

In the past I ran into a similar problem, however my question was a hyphen, I just replaced the hyphen with an underscore. you could do something like this, but seeing that it is an email address, it’s better to change the scheme (regular expression that receives Json from a third-party API), create a new β€œmail” key so that you can guarantee that your original email address mail will be saved.

But, perhaps more importantly, since you are requesting this API, perhaps you already knew this email if you could just replace regex:

  string json = '... {" joe@bobs.com ":...}...'; Regex regex = new Regex(@"\b[A-Za-z0-9._%+-] +@ [A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b"); string jsonfixed = regex.Replace(json, "email"); 
0
source

Source: https://habr.com/ru/post/989069/


All Articles