首页 > 解决方案 > 使用 Newtonsoft 进行序列化和反序列化时出错

问题描述

我想c#使用 Newtonsoft 序列化和反序列化模型。序列化运行良好,但反序列化抛出错误:Error converting value "1" to type ProjectNamespace.CapturedObject'. Path '', line 14, position 19.'Visual Studio 还说:Inner Exception: ArgumentException: Could not cast or convert from System.String to ProjectNamespace.CapturedObject. 我需要帮助来解释此错误消息。下面是相关的类......我从这里Json Extension Converter得到的线上抛出了错误return new Collection<T> { token.ToObject<T>() };

序列化/反序列化

public class JsonSession
    {    
        private readonly JsonSerializer serializer = new JsonSerializer();

        private static JsonSerializerSettings GetJsonSerializerSettings()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Objects,
                Converters = new List<JsonConverter>
                {
                    new StringEnumConverter()
                }
            };
            return settings;
        }

        JsonSerializerSettings writerSettings = GetJsonSerializerSettings();

        /// <summary>
        /// Constructor
        /// </summary>
        public JsonSession() { }


        /// <summary>
        /// Deserialization
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public JsonModel OpenModel(string filePath)
        {
            using (StreamReader file = File.OpenText(filePath))
                return (JsonModel)serializer.Deserialize(file, typeof(JsonModel));
        }


        /// <summary>
        /// Serialization
        /// </summary>
        /// <param name="model"></param>
        /// <param name="filePath"></param>
        public void SaveModel(JsonModel model, string filePath)
        {
            using (StreamWriter file = File.CreateText(filePath))
            using (var writer = new JsonTextWriter(file))
            {
                writer.Formatting = Formatting.Indented;
                serializer.Serialize(writer, model);
            }
        }

    }

json模型

公共类 JsonModel {

    [JsonProperty("head")]
    public JsonHeader Header { get; set; } = new JsonHeader();

    
    [JsonProperty("application")]
    public JsonApplication Application { get; set; } = new JsonApplication();

    
    [JsonProperty("knowledgebase")]
    public JsonBase JsonBase { get; set; } = new JsonBase();

    #endregion

    #region Constructors
    public JsonModel() { }

    public JsonModel(JsonHeader header, JsonBase jsonBase)
    {
        this.Header = header;
        this.JsonBase = jsonBase;
    }
}

知识库

#region Public Members

        
        [JsonProperty("features")]
        [JsonConverter(typeof(JsonConverterExtension<CapturedObject>))]
        public Collection<CapturedObject> Features { get; set; } = new Collection<CapturedObject>();

        
        [JsonProperty("faces")]
        [JsonConverter(typeof(JsonConverterExtension<CapturedObject>))]
        public Collection<CapturedObject> Faces { get; set; } = new Collection<CapturedObject>();

        
        [JsonProperty("edges")]
        [JsonConverter(typeof(JsonConverterExtension<CapturedObject>))]
        public Collection<CapturedObject> Edges { get; set; } = new Collection<CapturedObject>();

        
        [JsonProperty("vertices")]
        [JsonConverter(typeof(JsonConverterExtension<CapturedObject>))]
        public Collection<CapturedObject> Vertices { get; set; } = new Collection<CapturedObject>();

        
        [JsonProperty("dimensions")]
        [JsonConverter(typeof(JsonConverterExtension<CapturedObject>))]
        public Collection<CapturedObject> Dimensions { get; set; } = new Collection<CapturedObject>();
        
        #endregion

        #region Constructors

        public JsonBase() { }

        #endregion
    }

捕获的对象类

public class CapturedObject
{

    [JsonProperty("pseudonym")]
    public string Pseudonym { get; set; }

    [JsonProperty("name")]
    public string ObjectName { get; set; }

    [JsonProperty("type")]
    public ModelObjectType ObjectType { get; set; }

    #endregion

    #region Constructor

    public CapturedObject() { }

}

#Json 转换器扩展

class JsonConverterExtension<T> : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(List<T>));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            if (token.Type == JTokenType.Array)
            {
                return token.ToObject<Collection<T>>();
            }
            return new Collection<T> { token.ToObject<T>() };
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            List<object> list = new List<object>();

            if (value is IEnumerable)
            {

                var enumerator = ((IEnumerable)value).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    list.Add(enumerator.Current);
                }
            }

            // List<T> list = (List<T>)value;
            if (list.Count == 1)
            {
                value = list[0];
            }
            serializer.Serialize(writer, value);
        }
    }

#EDIT : 示例 Json

    {
  "head": {
    "author": "User",
    "date": "8-20-2020",
    "application": "App",
    "cad": "swx",
    "name": "C:\\Users\\User\\Desktop\\so.json",
    "location": "C:\\Users\\User\\Desktop\\so.json"
  },
  "application": {
    "name": "App",
    "language": "English",
    "versions": "1",
    "extensions": ".json"
  },
  "knowledgebase": {
    "features": [
      {
        "pseudonym": "Caster Casing",
        "name": "BoddExtrude1",
        "type": 22
      },
      {
        "pseudonym": "Wheel",
        "name": "Revolve2",
        "type": 22
      },
      {
        "pseudonym": "Corner Vertex",
        "name": "Fillet1",
        "type": 22
      }
    ],
    "vertices": {
      "pseudonym": "Corner Vertex",
      "name": "SpecialVertex",
      "type": 3
    },
    "dimensions": {
      "pseudonym": "Cool Dimension",
      "name": "D1@Sketch2",
      "type": 14
    }
  }
}

标签: c#json

解决方案


推荐阅读