栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

无法反序列化我的json

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

无法反序列化我的json

您可以使用json.net以

List<LocationChannelEvent>
显示的格式对a进行反序列化和重新序列化,只要您使用custom即可
JsonConverer
。这是必需的,因为默认情况下,对象集合在JSON数组之间进行序列化,但是在JSON中,对象集合以单个对象的紧凑形式进行序列化,其中对象属性名称已序列化在称为的字符串数组中仅出现一次
"structure"
,并且对象本身表示为值数组,内部数组与结构数组成1-1对应。

因此,如果您创建以下转换器:

public class StructuredListConverter<T> : JsonConverter{    const string typeName = "type";    const string structureName = "structure";    const string listName = "list";    public override bool CanConvert(Type objectType)    {        if (!typeof(ICollection<T>).IsAssignableFrom(objectType)) return false;        // This converter is only implemented for read/write collections.  So no arrays.        if (objectType.IsArray) return false;         return true;    }    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)    {        if (reader.TokenType == JsonToken.Null) return null;        var collection = existingValue as ICollection<T> ?? (ICollection<T>) serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();        var root = JObject.Load(reader);        var structure = root[structureName] == null ? null : root[structureName].ToObject<string []>();        if (structure == null) throw new JsonSerializationException("structure not found.");        var listToken = root[listName];        if (listToken == null || listToken.Type == JTokenType.Null) return collection;        var list = listToken as JArray;        if (list == null) throw new JsonSerializationException("list was not an array.");        if (list == null || list.Count == 0) return collection;        foreach (var item in list)        { if (item == null || item.Type == JTokenType.Null)     collection.Add(default(T)); else if (item.Type != JTokenType.Array)     throw new JsonSerializationException(string.Format("Item was not an array: {0}", item)); else     collection.Add(new JObject(item.Zip(structure, (i, n) => new JProperty(n, i))).ToObject<T>());        }        return collection;    }    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)    {        var contract = serializer.ContractResolver.ResolveContract(typeof(T)) as JsonObjectContract;        if (contract == null) throw new JsonSerializationException(string.Format("Type {0} is not mapped to a JSON object.", typeof(T)));        var collection = (ICollection<T>)value;        writer.WriteStartObject();        // Write item type        writer.WritePropertyName(typeName);        serializer.Serialize(writer, typeof(T));        // Write structure (property names)        var structure = contract.Properties.Where(p => p.Readable && !p.Ignored).Select(p => p.PropertyName).ToList();        writer.WritePropertyName(structureName);        serializer.Serialize(writer, structure);        // Write array of array of values        var query = collection .Select(i => i == null ? null : contract.Properties.Where(p => p.Readable && !p.Ignored).Select(p => p.ValueProvider.GetValue(i)));        writer.WritePropertyName(listName);        serializer.Serialize(writer, query);        writer.WriteEndObject();    }}

并如下定义数据模型:

public class LocationChannelEvent : Activity.Channel.Event{    public double Latitude { get; set; }    public double Longitude { get; set; }    public float? Distance { get; set; }    public float? Altitude { get; set; }    /// <summary>    /// Speed in m/s    /// </summary>    public float? Speed { get; set; }}public class Location{    [JsonConverter(typeof(StructuredListConverter<LocationChannelEvent>))]    public List<LocationChannelEvent> events { get; set; }}public class RootObject{    public Location location { get; set; }}

您将能够反序列化和重新序列化显示的JSON。

原型小提琴。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637360.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号