Skip to content

System.Text.Json.Serialization not Deserialize inheritance class #67641

@psychomonkey9

Description

@psychomonkey9

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

i have class:

public class SomeClass
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        [JsonConverter(typeof(ParameterConverter))]
        public Parameter parameter1{ get; set; }
    }
    
    public class Parameter
    {
       public ParameterType FieldType { get; set; }
    };
        
    public class FieldParameter : Parameter
    {
       public string FieldId { get; set; }
    }
    
    public enum ParameterType
    {
        Default,
        Field
    }

and this is example json:

{
      "id": 1,
      "name": "SomeName"
      "parameter1": {
        "fieldId": "SomeId",
  	  "fieldType": "Field"
      }
  }

When deserializing the whole class, I have a problem with property parameter 1. I see only default values.

i use ParameterConverter:

public class ParameterConverter: JsonConverter<Parameter>
     {
         public override ParameterRead(
             ref Utf8JsonReader reader,
             Type typeToConvert,
             JsonSerializerOptions options)
         {
             if (reader.TokenType == JsonTokenType.Null)
             {
                 return null;
             }
 
             Utf8JsonReader startReader = reader;
 
             using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
             JsonElement jsonObject = jsonDocument.RootElement;
             
             return JsonSerializer.Deserialize(ref startReader, typeof(FieldParameter)) as Parameter;
         }
 
         public override void Write(Utf8JsonWriter writer, Parameter value, JsonSerializerOptions options)
         {
             JsonSerializer.Serialize(writer, value, value.GetType());
         }
     }

but this Converter does not work. Why does the converter not see anything?

i expect to see {"fieldId": "SomeId","fieldType": "Field"}

i am use System.Text.Json.Serialization

more:
When i get string from jsonObject and i try manualy Deserialize, i see same result

string value = jsonObject.GetRawText();
var result2 = JsonSerializer.Deserialize<FieldParameter>(value)

.NET Version

5.0.15

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.Jsonneeds-author-actionAn issue or pull request that requires more info or actions from the author.no-recent-activityquestionAnswer questions and provide assistance, not an issue with source code or documentation.untriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions