chani chani - 4 months ago 12
C# Question

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

I'm trying to send an

HttpRequest
that takes a JSON object like this:

{
"some.setting.withperiods":"myvalue"
}


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
[DataMember(Name="some.setting.withperiods")]
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);
//{"some.setting.withperiods":"myvalue"}