问题
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 ?
回答1:
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 json.net and javascriptserializer and even datacontractjsonserializer 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 },
});
来源:https://stackoverflow.com/questions/53405088/output-a-json-property-name-with-a-dash-using-an-anonymous-object