如何使用当前会话将 JSON 反序列化为 XPO 对象?

问题描述

我已使用默认会话将 xpo 对象序列化为单独项目中的 JSON 数据。但是当我尝试在视图控制器中反序列化相同的内容时,我收到了默认会话错误。我能够获取当前会话,但我不确定如何使用当前会话进行反序列化。

Newtonsoft 被用于序列化和反序列化。

string filetext= File.ReadAllText("importedfile.json");
Plugin pl = (Plugin)JsonConvert.DeserializeObject(filetext,jsonsettings);

插件是我的类名,JSON 数据应该被反序列化。

解决方法

假设您的 Plugin 类型以 DevExpress.Xpo.XPObject 中所示的方式继承自 documentation example

public class Plugin : XPObject {
    // XPObject has a built-in Integer key and you can't add a custom key
    public Plugin(Session session) : base(session) { }
    string fMyProperty;
    public string MyProperty {
        get { return fMyProperty; }
        set { SetPropertyValue(nameof(fMyProperty),ref fMyProperty,value); }
    }
}

假设您的反序列化代码已经可以访问某些 Session session,然后定义以下 CustomCreationConverter<Plugin>

public class PluginConverter : CustomCreationConverter<Plugin>
{
    DevExpress.Xpo.Session Session { get; }

    public PluginConverter(DevExpress.Xpo.Session session) => this.Session = session ?? throw new ArgumentNullException();

    public override Plugin Create(Type objectType) => new Plugin(Session);
}

反序列化如下:

Session session; // Your session

var jsonsettings = new JsonSerializerSettings
{
    Converters = { new PluginConverter(session),/* Other converters as required */ },// Other settings as required
};
var pl = JsonConvert.DeserializeObject<Plugin>(filetext,jsonsettings);

反序列化类型 Plugin 时,将调用转换器的 Create() 方法以使用提供的会话制造 Plugin

如果您使用多个会话,则需要为每个新会话使用一个新的 JsonSerializerSettings

此模式可用于从 XPObject 继承的任何类型,其公共构造函数采用 Session 对象。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...