为什么Newtonsoft.JSON在每个元素的每个属性中都加上一个'$'符号?

时间:2013-02-27 22:05:20

标签: c# .net asp.net-mvc-4 json.net

我一直在使用来自King的 JSON ,我刚刚注意到,他为每个属性名称元素添加:

{ "$id": "1", "BackGroundColor": "#FFFFFF", "PageTitleFontColor": "#9C0912", "TitleDescriptionFontColor": "#715135", "TextTitleFontColor": "#715135", "ContentFontColor": "#646464", "VisiblePages": { "$id": "2", "$values": [ "About", "Gallery", "PriceList" ] } }

这是我设置它的方式:

JsonSerializerSettings jSettings = new JsonSerializerSettings
{
   PreserveReferencesHandling = PreserveReferencesHandling.All,
   Formatting = Formatting.Indented,
   DateTimeZoneHandling = DateTimeZoneHandling.Utc,
   ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
};

jSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

模型示例:

public class SettingsApiModel
{
    public virtual string BackGroundColor { get; set; }
    public virtual string PageTitleFontColor { get; set; }
    public virtual string TitleDescriptionFontColor { get; set; }
    public virtual string TextTitleFontColor { get; set; }
    public virtual string ContentFontColor { get; set; }
    public virtual IList<string> VisiblePages { get; set; } 
}

我实际上不喜欢每个属性的'$'。我该如何删除它?

1 个答案:

答案 0 :(得分:1)

您需要在PreserveReferencesHandling对象中更改正在使用的jSettings属性。您可以根本不设置此项,也可以将其设置为PreserveReferencesHandling.Objects

没有PreserveReferencesHandling设置:

{
    "BackGroundColor": "#FFFFFF",
    "PageTitleFontColor": "#9C0912",
    "TitleDescriptionFontColor": "#715135",
    "TextTitleFontColor": "#715135",
    "ContentFontColor": "#646464",
    "VisiblePages": [
        "About",
        "Gallery",
        "PriceList"
    ]
}

PreserveReferencesHandling = PreserveReferencesHandling.Objects

{
    "$id": "1",
    "BackGroundColor": "#FFFFFF",
    "PageTitleFontColor": "#9C0912",
    "TitleDescriptionFontColor": "#715135",
    "TextTitleFontColor": "#715135",
    "ContentFontColor": "#646464",
    "VisiblePages": [
        "About",
        "Gallery",
        "PriceList"
    ]
}