Help: Getting "JsonSerializationException: Unable to find a constructor to use" error when trying to deserialize on WebGL #68
-
Expected behaviorI have a basic JSON payload that I am attempting to deserialize into a known class. I would expect to be able to convert the following JSON payload:
Into an instance of the following class...
By using the following code:
Actual behaviorThis works fine when running in the Unity editor, but when I build for WebGL, I receive the following exception in the console...
Steps to reproduce
void Start() {
var json =
"{\"token\":\"f61886be-6d2b-49ec-81da-1cb184729849\",\"expiresAt\":\"2020-10-29T17:58:36.408293Z\",\"createdAt\":\"2020-10-14T17:58:36.408293Z\"}";
var accessTokenDto = JsonConvert.DeserializeObject<AccessTokenDto>(json);
Debug.Log(accessTokenDto.Token);
}
DetailsmacOS Catalina 10.15.6 WebGL 12.0.301 2019.4.9f1 Checklist
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hopefully I can answer my own question here. This turned out to be because Unity strips constructors and type parameters during the linking phase if they're not used. In order to negate this, you can use the Preserve attribute or a link.xml file. Adding
This may be something worthwhile adding to the README or Wiki. I'd be happy to do so if someone would like to point me to the right place to do it. Thanks! |
Beta Was this translation helpful? Give feedback.
-
Hi @JesseDunlap ! Thanks for reporting this :) This is a known issue with the package, and I have added it to this repos wiki: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Fix-AOT-compilation-errors I take full responsability in not making this knowledge more apparent. This is so common so I should indeed add this to the top of the README.md. It's good that you bring it up because I've forgotten to do so. If you have any comments on the wiki pages, don't fray to create issues on the matter. The better, the better |
Beta Was this translation helpful? Give feedback.
Hopefully I can answer my own question here. This turned out to be because Unity strips constructors and type parameters during the linking phase if they're not used. In order to negate this, you can use the Preserve attribute or a link.xml file.
Adding
[Preserve]
attributes to my DTO class and its fields solved the issue.This may be something worthwhile adding to the README or Wiki. I'd be happy to do so if someone would like to point me to the right place to do it. Tha…