JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.73k stars 3.25k forks source link

Getting error Object serialized to Uri. JObject instance expected #2874

Open ankis2 opened 1 year ago

ankis2 commented 1 year ago

Source/destination types

// Put the types you are serializing or deserializing here
Uri

Source/destination JSON

{https://localhost/}

{"message":"Place your serialized or deserialized JSON here"}

Expected behavior

Uri uri = new Uri("https://localhost"); Uri dce2 = SerializationHelper.Deserialize(SerializationHelper.Serialize(uri)); JToken.DeepEquals( JObject.FromObject(uri, JsonSerializer.Create(SerializationHelper.settings)), JObject.FromObject(dce2, JsonSerializer.Create(SerializationHelper.settings))); } JObject.FromObject fails with error: Object serialized to Uri. JObject instance expected.' I expected the JObject.FromObject to work without issues for both of the original issue and the roundtrip version.

Actual behavior

Steps to reproduce

// Your calls to Newtonsoft.Json here
ankis2 commented 1 year ago

We are using version 13.0.2

elgonzo commented 1 year ago

Please provide a code example reproducing the problem that does NOT use unknown code/functions like SerializationHelper.Serialize, SerializationHelper.Deserialize and SerializationHelper.settings. Don't leave anybody blindguessingf what these do...

Preferably, provide a code example directly runnable on https://dotnetfiddle.net/


That said, i guess(!) that since Uri's get serialized as json strings and not as json objects, JObject.FromObject is not appropriate here. Try JToken.FromObject(uri) instead (which should result in a JValue and not a JObject, since JValue is used to represent "simple" json value types like strings, numbers, booleans that are not complex/composite values like json arrays or json objects.)