3

我已经使用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; } 
}

我实际上不喜欢每个属性上的“$”。我怎样才能删除它?

4

1 回答 1

3

您需要更改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"
    ]
}
于 2013-02-28T06:33:02.150 回答