Help, my Unity HTTP-Requests break on UWP!

Jonas Hundertmark
medialesson
Published in
1 min readApr 11, 2023
Photo by Shannon Potter on Unsplash

Use Newtonsoft.Json for JSON serialization instead of System.Text.Json.

Short post today, because I haven’t seen it mentioned anywhere else and it cost me a bunch of time debugging. Calling JsonSerializer.Serialize() on UWP will throw an exception and stop your method call from executing. Curiously, JsonSerializer.Deserialize() seems to work without issue. If you know where to look, you can also find this open issue-thread from 2019 on GitHub. Bottom line, use Newtonsoft. Doesn’t seem like this problem will be fixed anytime soon.

Additionally, when working on UWP there seems to be a preference for Windows.Web.Http.HttpClient instead of the regular HttpClient. In my case, it didn’t really make a difference but I’m including a code snippet in here anyway so you don’t have to leave empty-handed. This simple example-class handles a Patch-Request to a predefined API-Endpoint. It uses System.Net.Http.HttpClient on Standalone, and Windows.Web.Http.HttpClient on UWP. I also included a custom Awaiter for IAsyncOperationWithProgress.

You can extend this snippet with method calls for POST-, PUT- or whatever else requests you need. But in general, yeah, simply switching to Newtonsoft should do the trick.

Cheers!

--

--