简体   繁体   中英

Why does Newtonsoft.JSON put a '$' sign in each property of each element?

I have been using JSON from the King for a long time, and I have just noticed, that he adds for each element that is a property name :

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

This is how I set it up:

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

The models example:

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

I actually don't like the '$' on each property. How can I remove it?

You need to change the PreserveReferencesHandling property you are using in the jSettings object. You can either not set this at all, or set it to 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"
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM