JSON.NET线序列化winrt [英] JSON.NET Line serialization winrt

查看:73
本文介绍了JSON.NET线序列化winrt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在序列化ObservableCollection of Lines(形状)时遇到了一些麻烦.我正在为Windows RT开发,并且正在使用JSON.NET v5.02.对于以下代码,我收到以下异常:

I'm having some trouble with serializing a ObservableCollection of Lines (Shape). I'm developing for Windows RT and I'm using JSON.NET v5.02. I'm getting the following exception for the code below:

ObservableCollection<Line> lines;
//some code
string linesString = JsonConvert.SerializeObjectAsync(lines); // problem

Newtonsoft.Json.JsonSerializationException类型的异常 发生在mscorlib.dll中,但未在用户代码中处理

An exception of type Newtonsoft.Json.JsonSerializationException occurred in mscorlib.dll but was not handled in user code

其他信息:从'X1'获取值时出错 "Windows.UI.Xaml.Shapes.Line".

Additional information: Error getting value from 'X1' on 'Windows.UI.Xaml.Shapes.Line'.

如果有用于此异常的处理程序,则该程序可能是安全的 继续.

If there is a handler for this exception, the program may be safely continued.

这是一个错误,有没有可能的解决方法?

Is this a bug and is there a possible workaround?

推荐答案

您的问题是跨线程问题.使用await JsonConvert.SerializeObjectAsync(lines);时,该功能将在另一个线程(而不是UI线程)中执行.由于Windows.UI.Xaml.Shapes.Line是UIElement,并且是在UI(主)线程中创建的,因此您无法在另一个线程中访问对象的属性.解决方案是将其转换为不受此限制的简单对象.

Your problem is a cross thread problem. When using await JsonConvert.SerializeObjectAsync(lines); that function will be executed in another thread (not the UI thread). Since a Windows.UI.Xaml.Shapes.Line is a UIElement and was created in the UI (main) thread you can't access the properties of the object in another thread. The solution would be to convert it to a simpler object that doesn't have this restrictions.

此外,Windows.UI.Xaml.Shapes.Line包含很多信息,可见性,IsEnabled等,我认为您只需要X1,X2,Y1和Y2.所以你可以使用这个:

Besides, a Windows.UI.Xaml.Shapes.Line contains a lot of information, Visibility, IsEnabled etc, I think you would only need the X1, X2, Y1 and Y2. So you could just use this:

string s = await JsonConvert.SerializeObjectAsync(lines
             .Select(l => new 
                     {
                         l.X1,
                         l.X2,
                         l.Y1,
                         l.Y2
                     }).ToArray()); 

通过这种方式,您可以在UI(主)线程中获得所需的属性.然后将该数组传递给序列化函数.这样就可以了.

In this way, you get the properties you need in your UI (main) thread. Then pass that array to the serialize function. This way it works.

string s现在将包含:

[{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0},{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2:40.0},{" X1:20.0," X2:20.0," Y1:40.0," Y2:40.0},{" X1:20.0," X2:20.0," Y1:40.0 ,"Y2":40.0}]

[{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0},{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0},{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0},{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0}]

这篇关于JSON.NET线序列化winrt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆