[英]How correctly serialize and deserialize List of objects in Json?
我有这样的BaseView
public abstract class BaseView
{
public enum ViewType
{
NOT_DEFINED,
CHECK_BOX
}
virtual public string Title { get; } = string.Empty;
virtual public string Name { get; } = string.Empty;
virtual public string ConfigName { get; } = string.Empty;
virtual public int DefaultValue { get; } = MCConstants.DEFAULT_VAL;
virtual public ViewType Type { get; } = ViewType.NOT_DEFINED;
public BaseView(string title, string configName, int defaultValue, ViewType viewType)
{
Title = title;
Name = title.Replace(' ', '_');
ConfigName = configName;
DefaultValue = defaultValue;
Type = viewType;
}
}
和他的孩子
public class DynamicCheckBox : BaseView
{
public bool IsChecked { get; set; }
public DynamicCheckBox(string title, string configName, int defaultValue) : base(title, configName, defaultValue, ViewType.CHECK_BOX)
{
IsChecked = DefaultValue == MCConstants.TRUE ? true : false;
}
}
现在我需要序列化DynamicCheckBox
List 然后反序列化它。 为此我写了这样的方法
public static string ParseObjListToString<TYPE>(IList<TYPE> list)
{
return JsonConvert.SerializeObject(new { list }); <--- This line
}
public static IList<TYPE> ParseStringToListOfObj<TYPE>(string value)
{
return JsonConvert.DeserializeObject<IList<TYPE>>(value);
}
我得到这样的错误
Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.IList`1[TV_MeshCreatorEngine.Base.BaseView]' 因为该类型需要一个JSON 数组(例如 [1,2,3])以正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为正常的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型)可以从 JSON 对象反序列化的数组或列表)。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“列表”,第 1 行,位置 8。
有我的测试方法
private void TestMethod()
{
IList<BaseView> list = new List<BaseView>()
{
new DynamicCheckBox("titleOne", "configNameOne", 1)
};
var stringResult = JsonUtil.ParseObjListToString(list);
IList<BaseView> listResult = JsonUtil.ParseStringToListOfObj<BaseView>(stringResult);
}
我究竟做错了什么?
编辑
如果我改变这个方法
public static string ParseObjListToString<TYPE>(IList<TYPE> list)
{
return JsonConvert.SerializeObject(new { list }); <--- This line
}
对此
public static string ParseObjListToString<TYPE>(IList<TYPE> list)
{
return JsonConvert.SerializeObject(list ); <--- This line
}
无论如何我得到错误
Newtonsoft.Json.JsonSerializationException: '无法创建 TV_MeshCreatorEngine.Base.BaseView 类型的实例。 类型是接口或抽象类,不能被实例化。 路径 '[0].IsChecked',第 1 行,位置 14。'
您正在使用类型为 IEnumerable<> 的名为 list 的字段序列化对象,而不是序列化为数组。
改变
return JsonConvert.SerializeObject(new { list });
到
return JsonConvert.SerializeObject(list);
编辑:因为您的输出 JSON 看起来像: { list: [] }
Newtonsoft.Json 无法将其反序列化为数组[]
您还可以更改反序列化以匹配您的序列化对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.