chani chani - 2 months ago 6
C# Question

How to create a json string where a property contains a dot (period)?

I'm trying to send an

that takes a JSON object like this:


I've been creating anonymous objects for my other requests, but I can't do that with this one since the name contains a dot.

I know I can create a class and specify the
attribute, but there must be a more lightweight solution.

Answer Source

There is no "easy" way to achieve this because the . in C# is reserved.

However, you could achieve something pretty close by using a dictionary and collection initializer. It's still somewhat isolated, and doesn't require you to create a custom class.

var obj = new Dictionary<string, object>
    { "some.setting.withperiods", "myvalue" }

var json = JsonConvert.SerializeObject(obj);