How to deserialize JSON to XPO objects using the current session?

623 views Asked by At

I have serialized xpo objects into JSON data in separate project using default session. But when I try to de-serialize the same within view controller i am getting default session error. I am able to get the current session but I am not sure how to deserialize by using the current session.

Newtonsoft is being used to serialize and deserialize.

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

Plugin is my class name to which the JSON data should get deserialized.

1

There are 1 answers

0
dbc On

Presuming your Plugin type inherits from DevExpress.Xpo.XPObject in the manner shown in the 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); }
    }
}

And assuming that your deserialization code already has access to some Session session, then define the following 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);
}

And deserialize as follows:

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);

When deserializing the type Plugin the converter's Create() method will be invoked to manufacture the Plugin using the provided session.

If you are using multiple sessions, you will need to use a new JsonSerializerSettings for each new session.

This pattern can be used for any type inheriting from XPObject with a public constructor taking a Session object.