ats*_*joo 2 c# json.net microsoft-metro windows-8.1
当我尝试使用Json.NET将json反序列化为我的自定义类型时,我遇到了一个奇怪的问题:
public class Shot
{
[JsonProperty("frames")]
public ObservableCollection<Frame> Frames
{
get { return Frames = _frames ?? new ObservableCollection<Frame>(); }
set { _frames = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
这产生了这个例外:
该API"System.Collections.ObjectModel.ObservableCollection
1[[AxisCtrl.Core.Model.Frame, AxisCtrl.Core.Logic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]..ctor(System.Collections.Generic.List1 [AxisCtrl.Core.Model.Frame])"不能在当前的平台上使用.有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=248273.
当我尝试从Windows 8.1 Windows应用商店应用程序中将json反序列化为此类型时,但在我的单元测试环境中的"类库"类型项目中运行时,它正在工作:
提到的网址已经死了,正在重定向到主页面,因此没有多大帮助.奇怪的是,在我开始将项目和类拆分为不同的结构之前,这是有效的.但是我没有移动Shot类或更改它包含的项目类型.
Shot类在".NET Framework 4.5及更高版本","Windows应用商店应用程序(Windows 8)及更高版本"和"Windows Phone 8"的可移植类库类型项目中定义,主项目是Windows 8.1应用程序.
关于这里发生了什么的任何想法?
问题是JSON.NET用于ObservableCollection的ctor在WinRT中是不可用的
http://msdn.microsoft.com/en-us/library/ms668604%28v=vs.110%29.aspx
您可以通过覆盖合同解析程序来绕过此问题
ContractResolver : DefaultContractResolver
{
public override JsonContract ResolveContract(Type type)
{
//check if type is ObservableCollection
if (type.GetTypeInfo().IsGenericType
&& type.GetTypeInfo().GetGenericTypeDefinition()
== typeof(ObservableCollection<>))
{
//use list as default contract
var c = (JsonArrayContract)
base.ResolveContract(typeof(List<>)
.MakeGenericType(type.GenericTypeArguments[0]));
//use Activator to create instance
c.DefaultCreator = () => Activator.CreateInstance(type);
return c;
}
else return base.ResolveContract(type);
}
}
Run Code Online (Sandbox Code Playgroud)
然后设置合同解析器的实例JsonSettings或JsonSerializer调用的属性ContractResolver.
| 归档时间: |
|
| 查看次数: |
1462 次 |
| 最近记录: |