Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

json.net

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.

like image 358
chani Avatar asked Dec 14 '22 23:12

chani


1 Answers

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"}
like image 194
Xenolightning Avatar answered May 27 '23 18:05

Xenolightning