0

I am using a third party API which is like this below. It uses Json serializer to output

public Output(string name, object value);

I have to place the following json string in my output file from C#

Output("somename", new {my-name : "somevalue"})

The issue is C# does not allow identifiers with dash (-). How do I achieve this ?

Tried putting raw value like below but it adds back slash (\) to the file output which is not going very well.

Output("somename", @"{""my-name"":""somevalue""}")

Any thoughts ?

Brian Rogers
  • 118,414
  • 30
  • 277
  • 278
Frank Q.
  • 5,080
  • 10
  • 43
  • 57
  • What third party serializer, i am having a lot of trouble understanding this question, however it could be just me – TheGeneral Nov 21 '18 at 04:05
  • 1
    Why not just use a dictionary? `new Dictionary { { "my-name", "somevalue" } }` – dbc Nov 21 '18 at 04:10
  • Since you have tagged this [tag:json.net], it is probably a duplicate of [How can I parse a JSON string that would cause illegal C# identifiers?](https://stackoverflow.com/q/24536533/3744182). Agree? – dbc Nov 21 '18 at 04:14
  • @dbc put it as answer. That works. – Frank Q. Nov 21 '18 at 16:33

1 Answers1

3

Since you are using an anonymous object, the simplest workaround would be to create a Dictionary<string, string> instead:

Output("somename", new Dictionary<string, string> { { "my-name", "somevalue" } });

Serialization of a dictionary as a JSON object in which the dictionary keys are mapped to JSON property names is supported by many .Net JSON serializers including and and even when UseSimpleDictionaryFormat = true as noted here.

And if you have values of different types and are using a serializer that supports arbitrary polymorphism during serialization (Json.NET and JavaScriptSerializer do) you could use a Dictionary<string, object>:

Output("somename",
    new Dictionary<string, object>
    {
        { "my-name", "somevalue" },
        { "my-id", 101 },
        { "my-value", value },
    });
dbc
  • 91,441
  • 18
  • 186
  • 284