使用Newtonsoft.Json进行强制转换

时间:2016-03-30 09:50:50

标签: c# json rest serialization json.net

之前,我使用IDataContractSurrogate来序列化我的数据,但它与CPL(便携式类librairy)不兼容,所以我现在正在使用Newtonsoft。

但是,我必须将一个ObservableCollection类型转换为List with:

myobj [ { id:1, name="test1", value="test_1"}, { id:2, name="test2", value="test_2"}]

myobj ["test1", "test2"],

有可能吗? 我试过这样:

public class ccrUser : DefaultContractResolver { // Newtonsoft.Json.Serialization.IContractResolver

        private bool toSerialise;
        public static readonly ccrUser Instance = new ccrUser(true);

        /// <summary>Constructeur</summary>
        /// <param name="pToSerialise">Indique le sens qui sera utlisé (les API ne donnent pas le même format en GET qu'elles attendent en POST).</param>
        public ccrUser(bool pToSerialise) : base() { toSerialise = pToSerialise; }

        protected override JsonContract CreateContract(Type objectType) {
            var contract = base.CreateContract(objectType);
            if ((toSerialise) && (objectType == typeof(ObservableCollection<tblGroup>))) {
                //contract.Converter = new Newtonsoft.Json.Converters.CustomCreationConverter<string>();
                return base.CreateArrayContract(objectType);
            } else
                return contract;
        }
        protected override List<MemberInfo> GetSerializableMembers(Type objectType) {
            var defaultMembers = base.GetSerializableMembers(objectType);
            if ((toSerialise) && (objectType == typeof(ObservableCollection<tblGroup>))) {
                return defaultMembers;
            } else
                return defaultMembers;
        }


        protected override JsonConverter ResolveContractConverter(Type objectType) {
            if (objectType == typeof(ObservableCollection<tblGroup>)) {
                return null; // pretend converter is not specified
            }
            return base.ResolveContractConverter(objectType);
        }

        /// <summary>JSON value provider that always returns a static value</summary>
        public class StaticValueProvider : IValueProvider {
            private readonly object _staticValue;
            public StaticValueProvider(object staticValue) {  _staticValue = staticValue; }
            public void SetValue(object target, object value) { throw new NotSupportedException(); }
            public object GetValue(object target) { return _staticValue; }
        }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            if ((toSerialise) && (property.PropertyType == typeof(ObservableCollection<tblGroup>))) {
            }
            return property;
        }
    }

但无法找到解决方案。

此致

2 个答案:

答案 0 :(得分:0)

不是在序列化/反序列化过程中进行转换,而是可以序列化/反序列化另一个属性(另一种类型):

\w*\s\w*

// serialize only marked members [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class SerializableObject { // original property: not serialized public TypeA PropertyA { get; set; } [JsonProperty(nameof(PropertyA))] public TypeB PropertyB { get { // convert PropertyA value to TypeB return (TypeB)PropertyA; } set { // convert TypeB to TypeA and set PropertyA value PropertyA = (TypeA)value; } } } (如果您愿意,可以是PropertyB)仅用于将private值序列化/反序列化为另一种类型。

答案 1 :(得分:0)

有一个编译错误,它无法解析List&lt;字符串&gt;到IEnumerable&lt; tblGroup&gt; :

    [DataMember(Name ="groups")] 
public List<string> groupsApi { get { return (from c in (ObservableCollection<tblGroup>)_groups select c.value).ToList(); } set { _groups = new ObservableCollection<tblGroup>(value); } } 
public ObservableCollection<tblGroup> groups { get { return _groups; } set { _groups = value; } }