【发布时间】:2020-01-20 09:46:13
【问题描述】:
我有这样的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 的列表,然后反序列化它。为此我写了这样的方法
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 位。'
【问题讨论】:
-
我认为您在方法中序列化了列表列表。你可以用这个代替吗? return JsonConvert.SerializeObject(list);
-
这能回答你的问题吗? Deserializing JSON to abstract class
标签: c#