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: 3 comments 2 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.
Here's an example implementation of a
JsonConverter
that can be used to serialize and deserializeJToken
objects using the System.Text.Json library: