7

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?

2
  • 2
    This behavior is explained exactly in Deserialize inferred types to object properties article. Did you try to follow it and write own JsonConverter<object>? Commented Aug 15, 2020 at 18:15
  • Thanks Pavel, looks like I've missed this article in the documentation. Commented Aug 15, 2020 at 18:38

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.