如何在属性包含点(句点)的情况下创建json字符串? [英] How to create a json string where a property contains a dot (period)?

查看:110
本文介绍了如何在属性包含点(句点)的情况下创建json字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发送一个带有如下JSON对象的HttpRequest:

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.

我知道我可以创建一个类并指定[DataMember(Name="some.setting.withperiods")]属性,但是必须有一个更轻量的解决方案.

I know I can create a class and specify the [DataMember(Name="some.setting.withperiods")] attribute, but there must be a more lightweight solution.

推荐答案

没有实现此目的的简便"方法,因为C#中的.是保留的.

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

这篇关于如何在属性包含点(句点)的情况下创建json字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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