使用匿名对象输出带破折号的JSON属性名称 [英] Output a JSON property name with a dash using an anonymous object

查看:131
本文介绍了使用匿名对象输出带破折号的JSON属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第三方API,如下所示.它使用Json serializer输出

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

public Output(string name, object value);

我必须将以下json字符串放入C#的输出文件中

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

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

问题是C#不允许带破折号(-)的标识符.我该如何实现?

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

尝试按如下所示放置原始值,但它会将back slash (\)添加到文件输出中,效果不佳.

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""}")

有什么想法吗?

推荐答案

由于您使用的是匿名对象,所以最简单的解决方法是创建Dictionary<string, string>:

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" } });

许多.Net JSON序列化程序(包括甚至,当此处.

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.

如果您具有不同类型的值,并且正在使用在序列化期间支持任意多态性的序列化程序(Json.NET和JavaScriptSerializer可以),则可以使用Dictionary<string, object>:

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 },
    });

这篇关于使用匿名对象输出带破折号的JSON属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆