Hacker News new | ask | show | jobs
by WorldMaker 1478 days ago
This is where the C# `dynamic` keyword sometimes shines. It's a lesser known feature from a project called the DLR that tried to shake up the CLR to better support more languages like IronPython and IronRuby. Both IronPython and IronRuby kind of got scrapped/pushed aside, and the DLR never quite got the love it deserved, but what remains is still sometimes useful. If you are still using JSON.NET (Newtonsoft.JSON) (which you did mention its JSON LINQ JObject/JToken, etc.), it still supports the `dynamic` operator for working with JSON "more naturally":

  dynamic jsonObject = JObject.Parse(someJsonString);
  jsonObject.some.deep[1].propertyName = "Updated string";
  return jsonObject.ToString(); // re-serialize the updated JSON
You don't get much IntelliSense when using dynamic, but it makes it much easier to write what you want/expect to write with a JSON object than if you were navigating the JSON LINQ (JObject/JToken/etc) objects by hand.

The documentation still includes pages on dynamic, even though dynamic has become a mostly forgotten feature and there are still developers that would never use dynamic. For example: https://www.newtonsoft.com/json/help/html/QueryJsonDynamic.h...

I appreciate that dynamic exists in C#. I've done some wild things with dynamic over the years. It sometimes makes me sad how under-appreciated a tool it can be.

ETA: Obviously dynamic is not type-safe, it's a great escape hatch from type safety for small cases where "just do what I want" is nicer/more natural than type safety. As the sibling comment points out, if you still prefer type safety there are type deserializers that can be easier to use. These days with records in C# 9+ writing quick types to deserialize to is even relatively painless.