为什么Newtonsoft.JSON在每个元素的每个属性中都放了一个"$"号?



我一直在使用来自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; } 
}

我其实不喜欢每个属性上的"$"。我怎样才能去掉它?

您需要更改您在jSettings对象中使用的PreserveReferencesHandling属性。可以不设置,也可以设置为PreserveReferencesHandling.Objects

No PreserveReferencesHandling setting:

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

相关内容

  • 没有找到相关文章

最新更新