Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text.Json object array deserialization

I'm trying to deserialize JSON such as this:

{ "Parameters": [ 1, "2", true, false, null ] }

using System.Text.Json serializer. Target class looks like this:

public class Payload {
    public object[] Parameters { get; set; }
}

Parameters are always primitive values like numbers, strings, booleans, etc. But looks like System.Text.Json populates my Parameters array with JsonElement values instead of plain scalar values. Here is the code sample:

var payload = new Payload {
    Parameters = new object[] {
        1, "2", true, false, null
    }
};

var json = JsonSerializer.Serialize(payload);
// result: {"Parameters":[1,"2",true,false,null]}

var deserialized = JsonSerializer.Deserialize<Payload>(json);
// result: deserialized.Parameters are all `JsonElement` values

The code that consumes the Payload class doesn't depend on System.Text.Json, it is serializer-agnostic. Is there a way to deserialize the array of objects using System.Text.Json and get back plain scalar values instead of JsonElements?

like image 621
yallie Avatar asked Aug 08 '26 13:08

yallie


1 Answers

An indication how it can be done. Will deserialize test data correctly if we can live with int64 for numbers, but still just a POC.

public class ObjectConverter : JsonConverter<object>
{
  public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  {
    return reader.TokenType switch
    {
      JsonTokenType.Number => reader.GetInt64(),
      JsonTokenType.String => reader.GetString(),
      JsonTokenType.True => reader.GetBoolean(),
      JsonTokenType.False => reader.GetBoolean(),
      _ => null
    };
  }

   public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
   {
      throw new NotImplementedException();
   }
 }

 public class Payload {
   public object[] Parameters { get; set; }
 }

 var payload = new Payload
 {
   Parameters = new object[] { 1, "2", true, false, null }
 };

 var json = JsonSerializer.Serialize(payload);
 var serializeOptions = new JsonSerializerOptions();
 serializeOptions.Converters.Add(new ObjectConverter());
 var deserialized = JsonSerializer.Deserialize<Payload>(json, serializeOptions);
like image 60
Roar S. Avatar answered Aug 10 '26 07:08

Roar S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!