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

Default values for values that didn't exist #47

Closed
denchInside opened this issue Mar 14, 2022 · 1 comment
Closed

Default values for values that didn't exist #47

denchInside opened this issue Mar 14, 2022 · 1 comment

Comments

@denchInside
Copy link

denchInside commented Mar 14, 2022

If the json payload does not have some values to serialize them into a struct, how to set such values to a custom default?
Nullable types aren't the choice because I use .net framework 4.5.

@denchInside denchInside changed the title About struct parsing Default values for values that didn't exist Mar 17, 2022
@denchInside
Copy link
Author

denchInside commented Mar 20, 2022

Well, I have solved the problem by changing 3 lines of code:

  1. use a class instead of a struct
  2. use a predefined field (this would be the default value) and a property referencing it instead of an automatic property ( {get; set;} )
  3. in JSONParser.cs, line 334, change object instance = FormatterServices.GetUninitializedObject(type) (analog to default(type)) to object instance = Activator.CreateInstance(type); (analog to new ClassName().)
    Now, the predefined values will stay untouched.

This variant wouldn't work for classes which doesn't have empty constructors.
So, maybe you will need to add object defaultObject into parameters of public static T FromJson<T>(this string json) (and put the defaultObject to all ParseObject() calls) and static object ParseObject(Type type, string json) (and set object instance to the defaultObject too) to manually set the default object if needed.

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

1 participant