Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deserialize H5 Newtownsoft Json to deserialize a derived type class? #80

Open
Riccsson opened this issue Mar 8, 2023 · 3 comments
Open

Comments

@Riccsson
Copy link

Riccsson commented Mar 8, 2023

Is there any way to use H5 Newtownsoft Json to deserialize a derived type class?

Store the class type as a json-property and do a custom deserialize and check the property to create instance of correct type class?
Any ideas?

@ghost
Copy link

ghost commented Mar 8, 2023

I afraid no, H5 version is very limited.

The single option is to use implicit cast operator.

If it is OK for you to pass data as string and restore object from string using cast operator.
Then H5 JsonConvert will try to find cast operator and use it. So creation of object will be your responsibility and in your control.

@theolivenbaum
Copy link
Collaborator

theolivenbaum commented Mar 8, 2023

You can store the type info in the json using a custom JsonSerializerSettings:

var jsonSettings = new JsonSerializerSettings 
                      {
                          TypeNameHandling = TypeNameHandling.Objects, 
                          SerializationBinder = AssemblyNameIgnoringSerializationBinder.Instance
                      };

var json = JsonConvert.SerializeObject(derivedObject, jsonSettings);
var deserialized = JsonConvert.DeserializeObject<BaseType>(json, jsonSettings);

@ghost
Copy link

ghost commented Mar 9, 2023

You can store the type info in the json using a custom JsonSerializerSettings:

var jsonSettings = new JsonSerializerSettings 
                      {
                          TypeNameHandling = TypeNameHandling.Objects, 
                          SerializationBinder = AssemblyNameIgnoringSerializationBinder.Instance
                      };

var json = JsonConvert.SerializeObject(derivedObject, jsonSettings);
var deserialized = JsonConvert.DeserializeObject<BaseType>(json, jsonSettings);

Hmm, I never seen this option before. For example IContractResolver is empty, also we missing DataConverters.

Though as I see you cannot decide inside binder which Type to provide depending on data (only on type name):

public interface ISerializationBinder
  {
    Type BindToType(string assemblyName, string typeName);

    void BindToName(Type serializedType, out string assemblyName, out string typeName);
  }

Probably it is possible to provide different binders depending on manually extracted data. Is it the idea?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants