Workaround for providing support for types JObject with System.Text.Json #82180
-
We are migrating our code base from Newtonsoft to System.Text.Json. While testing this migration effort, we have encountered errors while working with Newtonsoft.Json.Linq.JObject objects Issue during serialization:
We observed that while serializing the data using System.Text.Json, the key is present in the serialized data, but the values are not. Issue during de-serialization: Can you please share a workaround for providing support for JObject type with System.Text.Json? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 4 replies
-
The analog for There's also |
Beta Was this translation helpful? Give feedback.
-
Here's an example implementation of a public class JTokenConverter : JsonConverter<JToken>
{
public override bool CanConvert(Type typeToConvert) => typeof(JToken).IsAssignableFrom(typeToConvert);
public override JToken Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Use JsonDocument to parse the JSON and create a JToken from it
using JsonDocument document = JsonDocument.ParseValue(ref reader);
return JToken.Parse(document.RootElement.GetRawText());
}
public override void Write(Utf8JsonWriter writer, JToken value, JsonSerializerOptions options)
{
// Write the raw JSON from the JToken to the writer
writer.WriteRawValue(value.ToString());
}
} |
Beta Was this translation helpful? Give feedback.
-
What worked for me was converting the JObject to a dictionary with this code: public static Dictionary<string, object> ToDictionary(JObject jObject)
{
var dictionary = new Dictionary<string, object>();
foreach (var property in jObject)
{
dictionary[property.Key] = ToObject(property.Value);
}
return dictionary;
}
public static object ToObject(JToken token)
{
if (token.Type == JTokenType.Object)
{
return ToDictionary((JObject)token);
}
else if (token.Type == JTokenType.Array)
{
return ((JArray)token).ToObject<object[]>();
}
else
{
return ((JValue)token).Value;
}
} |
Beta Was this translation helpful? Give feedback.
-
i have a simlar... migration project which should be kicked off... but with that i see it as, the refernace to newtonsoft have to be remove.... which requires both the producer and the consumer to stop using newtonsoft object. im wondering, even if you get system.text.json to take a sting and then convert to a newton type, you still using a newton type and not removing the depenacy.. can someone help me understand the conversion plan here.. like you can create JsonConverter, but how does that help, im clearly missing something. @snjosephms |
Beta Was this translation helpful? Give feedback.
Here's an example implementation of a
JsonConverter
that can be used to serialize and deserializeJToken
objects using the System.Text.Json library: