Output a JSON property name with a dash using an anonymous object

回眸只為那壹抹淺笑 提交于 2019-12-20 07:18:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!