<small id='gBgA0'></small><noframes id='gBgA0'>

    <tfoot id='gBgA0'></tfoot>
    <i id='gBgA0'><tr id='gBgA0'><dt id='gBgA0'><q id='gBgA0'><span id='gBgA0'><b id='gBgA0'><form id='gBgA0'><ins id='gBgA0'></ins><ul id='gBgA0'></ul><sub id='gBgA0'></sub></form><legend id='gBgA0'></legend><bdo id='gBgA0'><pre id='gBgA0'><center id='gBgA0'></center></pre></bdo></b><th id='gBgA0'></th></span></q></dt></tr></i><div id='gBgA0'><tfoot id='gBgA0'></tfoot><dl id='gBgA0'><fieldset id='gBgA0'></fieldset></dl></div>

    1. <legend id='gBgA0'><style id='gBgA0'><dir id='gBgA0'><q id='gBgA0'></q></dir></style></legend>

        <bdo id='gBgA0'></bdo><ul id='gBgA0'></ul>

      Json.net 将属性添加到包含某种类型的每个类

      Json.net Add property to every class containing of a certain type(Json.net 将属性添加到包含某种类型的每个类)
        <i id='MSsmb'><tr id='MSsmb'><dt id='MSsmb'><q id='MSsmb'><span id='MSsmb'><b id='MSsmb'><form id='MSsmb'><ins id='MSsmb'></ins><ul id='MSsmb'></ul><sub id='MSsmb'></sub></form><legend id='MSsmb'></legend><bdo id='MSsmb'><pre id='MSsmb'><center id='MSsmb'></center></pre></bdo></b><th id='MSsmb'></th></span></q></dt></tr></i><div id='MSsmb'><tfoot id='MSsmb'></tfoot><dl id='MSsmb'><fieldset id='MSsmb'></fieldset></dl></div>
        <legend id='MSsmb'><style id='MSsmb'><dir id='MSsmb'><q id='MSsmb'></q></dir></style></legend>

              <tbody id='MSsmb'></tbody>

              <bdo id='MSsmb'></bdo><ul id='MSsmb'></ul>

              <small id='MSsmb'></small><noframes id='MSsmb'>

              <tfoot id='MSsmb'></tfoot>
              1. 本文介绍了Json.net 将属性添加到包含某种类型的每个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                问题描述

                限时送ChatGPT账号..

                我想为每个 DateTime 类型的属性在我的 json 中添加一个属性.

                I want to add a property to my json for every property of type DateTime.

                我有一个自定义转换器并覆盖了 CreateProperties(见下文).调试时返回的属性列表包含新值,但当 json 到达浏览器时,它不包含新属性

                I have a custom converter and have an override on CreateProperties (see below). When debugging the returned list of properties holds the new values but by the time the json reaches the browser it does not contain the new properties

                    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
                    {
                        var properties = base.CreateProperties(type, memberSerialization);
                
                        foreach(var prop in base.CreateProperties(type, memberSerialization))
                        {
                            if(prop != null
                                && (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?)))
                            {
                                properties.Add(new JsonProperty() {
                                    PropertyName = String.Format("{0}$$type", prop.PropertyName),
                                    PropertyType = typeof(String)
                                });
                            }
                        }
                        return properties;
                    }
                

                首先想到的是,新的 Json 属性随后会被清除,因为它们是无效的.可能是因为它们没有价值,但是我看不到在这里设置值.

                The first thing that comes to mind is that the new Json properties are being wiped off afterwards because they are invalid. Possibly because they have no value, however I can see no way to set the value here.

                欢迎任何想法

                推荐答案

                您正在尝试通过 自定义合约解析器.您的问题是您没有完全初始化 JsonProperty.至少你必须初始化

                You are trying to add a synthetic read-only property to your serialized JSON via a custom contract resolver. Your problem is that you are not fully initializing the required values of JsonProperty. At the minimum you must initialize

                • PropertyTypePropertyName.您已经在这样做了.
                • 可读trueWritable.
                • ValueProvider 到一些适当的自定义IValueProvider 的实现,它返回您的值希望在 JSON 中查看正在序列化的对象.

                另外,建议初始化:

                • AttributeProvider 到自定义实现IAttributeProvider 返回空的属性集合.
                • DeclaringType, UnderlyingName, ItemIsReferenceTypeNameHandling 到合理的地方.

                以下是这样做的,添加一个值为 "DateTime" 的固定字符串属性:

                The following does this, adding a fixed string property with the value "DateTime":

                public class AddDateTypeFlagContractResolver : DefaultContractResolver
                {
                    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
                    {
                        var properties = base.CreateProperties(type, memberSerialization);
                        for (int i = 0, n = properties.Count; i < n; i++)
                        {
                            var prop = properties[i];
                            if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
                            {
                                var name = string.Format("{0}$$type", prop.PropertyName);
                                var newProp = new JsonProperty
                                {
                                    DeclaringType = type,
                                    PropertyName = name,
                                    UnderlyingName = name,
                                    PropertyType = typeof(string),
                                    ValueProvider = new FixedValueProvider("DateTime"), // Replace with yout desired string value.
                                    AttributeProvider = NoAttributeProvider.Instance,
                                    Readable = true,
                                    Writable = false,
                                    // Ensure PreserveReferencesHandling and TypeNameHandling do not apply to the synthetic property.
                                    ItemIsReference = false, 
                                    TypeNameHandling = TypeNameHandling.None,
                                };
                                properties.Add(newProp);
                            }
                        }
                
                        return properties;
                    }
                }
                
                public class FixedValueProvider : IValueProvider
                {
                    readonly object value;
                
                    public FixedValueProvider(object value)
                    {
                        this.value = value;
                    }
                
                    #region IValueProvider Members
                
                    public object GetValue(object target) { return value; }
                
                    public void SetValue(object target, object value)
                    {
                        throw new NotImplementedException("SetValue not implemented for fixed properties; set JsonProperty.Writable = false.");
                    }
                
                    #endregion
                }
                
                class NoAttributeProvider : IAttributeProvider
                {
                    static NoAttributeProvider() { instance = new NoAttributeProvider(); }
                
                    static readonly NoAttributeProvider instance;
                
                    public static NoAttributeProvider Instance { get { return instance; } }
                
                    public IList<Attribute> GetAttributes(Type attributeType, bool inherit) { return new Attribute[0]; }
                
                    public IList<Attribute> GetAttributes(bool inherit) { return new Attribute[0]; }
                }
                

                然后,给定以下示例类型:

                Then, given the following example type:

                public class Example
                {
                    public string NotADate { get; set; }
                    public DateTime ADate { get; set; }
                    public DateTime? AnotherDate { get; set; }
                }
                

                生成以下 JSON:

                {
                  "NotADate": "a value",
                  "ADate": "2017-04-23T14:25:43.511-04:00",
                  "AnotherDate": "2017-04-23T14:25:43.511-04:00",
                  "ADate$$type": "DateTime",
                  "AnotherDate$$type": "DateTime"
                }
                

                它也是基于其他一些属性创建一个合成属性.例如,以下为模型中的每个 DateTime 属性添加一个 Date 属性:

                It is also to create a synthetic property based on some other property. For instance, the following adds a Date property for every DateTime property in the model:

                public class AddDateFromDateTimeContractResolver : DefaultContractResolver
                {
                    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
                    {
                        var properties = base.CreateProperties(type, memberSerialization);
                        for (int i = 0, n = properties.Count; i < n; i++)
                        {
                            var prop = properties[i];
                            if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
                            {
                                var name = string.Format("{0}$$date", prop.PropertyName);
                                var newProp = new JsonProperty
                                {
                                    DeclaringType = type,
                                    PropertyName = name,
                                    UnderlyingName = name,
                                    PropertyType = prop.PropertyType,
                                    ValueProvider = new DateTimeToDateValueProvider(prop.ValueProvider),
                                    AttributeProvider = NoAttributeProvider.Instance,
                                    Readable = true,
                                    Writable = false,
                                    // Ensure PreserveReferencesHandling and TypeNameHandling do not apply to the synthetic property.
                                    ItemIsReference = false,
                                    TypeNameHandling = TypeNameHandling.None,
                                };
                                properties.Add(newProp);
                            }
                        }
                
                        return properties;
                    }
                }
                
                public class DateTimeToDateValueProvider : ValueProviderDecorator
                {
                    public DateTimeToDateValueProvider(IValueProvider baseProvider) : base(baseProvider) { }
                
                    public override object GetValue(object target)
                    {
                        var baseValue = base.GetValue(target);
                        if (baseValue is DateTime)
                        {
                            return ((DateTime)baseValue).Date;
                        }
                        return baseValue;
                    }
                
                    public override void SetValue(object target, object value)
                    {
                        throw new NotImplementedException();
                    }
                }
                
                public abstract class ValueProviderDecorator : IValueProvider
                {
                    readonly IValueProvider baseProvider;
                
                    public ValueProviderDecorator(IValueProvider baseProvider)
                    {
                        if (baseProvider == null)
                            throw new ArgumentNullException();
                        this.baseProvider = baseProvider;
                    }
                
                    public virtual object GetValue(object target) { return baseProvider.GetValue(target); }
                
                    public virtual void SetValue(object target, object value) { baseProvider.SetValue(target, value); }
                }
                

                请注意,值提供者是通过将原始属性的值提供者包装在一个装饰器中来创建的,该装饰器将其值转换为所需的结果.另请注意,JsonProperty.PropertyType 设置为要返回的预期类型.使用此合约解析器,从 Example 类型生成以下 JSON:

                Notice that the value provider is created by wrapping the value provider of the original property in a decorator that transforms its value to the required result. Notice also that JsonProperty.PropertyType is set to the expected type to be returned. Using this contract resolver, the following JSON is generated from the Example type:

                {
                  "NotADate": "a value",
                  "ADate": "2017-04-23T14:25:43.511-04:00",
                  "AnotherDate": "2017-04-23T14:25:43.511-04:00",
                  "ADate$$date": "2017-04-23T00:00:00-04:00",
                  "AnotherDate$$date": "2017-04-23T00:00:00-04:00"
                }
                

                示例 fiddle 展示了两个合约解析器.

                Sample fiddle demonstrating both contract resolvers.

                这篇关于Json.net 将属性添加到包含某种类型的每个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                相关文档推荐

                Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
                Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
                Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
                How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
                how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
                JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)
                <i id='PH99G'><tr id='PH99G'><dt id='PH99G'><q id='PH99G'><span id='PH99G'><b id='PH99G'><form id='PH99G'><ins id='PH99G'></ins><ul id='PH99G'></ul><sub id='PH99G'></sub></form><legend id='PH99G'></legend><bdo id='PH99G'><pre id='PH99G'><center id='PH99G'></center></pre></bdo></b><th id='PH99G'></th></span></q></dt></tr></i><div id='PH99G'><tfoot id='PH99G'></tfoot><dl id='PH99G'><fieldset id='PH99G'></fieldset></dl></div>

                  <small id='PH99G'></small><noframes id='PH99G'>

                  <legend id='PH99G'><style id='PH99G'><dir id='PH99G'><q id='PH99G'></q></dir></style></legend>

                    <tfoot id='PH99G'></tfoot>

                        <bdo id='PH99G'></bdo><ul id='PH99G'></ul>

                            <tbody id='PH99G'></tbody>