-1

The code for serialization is:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;

namespace TxtToXmlParser.Parser
{
    public static class JSONserializerService
    {
        public static void Serialize<T>(string filePath,T data)
        {
            var jsonString = JsonSerializer.Serialize(data);
            //Console.WriteLine(jsonString);
            using FileStream fs = File.OpenWrite(filePath);
            byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
            fs.Write(bytes, 0, bytes.Length);
        }
    }    
}

First I create class Person, Student and Professor. Student and Professor inherits Class Person. I use parse data of that classes and serialize it to JSON file. I only get property of Person class (ex. "OIB":"001212","Name":"Iva Ivi\u0107","Date":"1998-02-02T00:00:00","Gender":1) but not "Grade":"4.3" which is only Student property.

I got this file:

[{"OIB":"001212","Name":"Iva Ivi\u0107","Date":"1998-02-02T00:00:00","Gender":1},{"OIB":"001213","Name":"Ivan Zoraja","Date":"1961-01-01T00:00:00","Gender":0}]

But I need to get:

[{"OIB":"001212","Name":"Iva Ivi\u0107","Date":"1998-02-02T00:00:00","Gender":1,**"Grade":"4.3"**},{"OIB":"001213","Name":"Ivan Zoraja","Date":"1961-01-01T00:00:00","Gender":0, **"Salary":"10020.00"**}]

Student class:

public  class Student : Person
{
    public float AvgGrade { get;  set; }
    public Student() { }

    public Student(float avgGrade, string oIB, string name, Gender gender, DateTime date) : base(oIB, name, gender, date)
    {
        AvgGrade = avgGrade;
    }
}

Person Class:

public abstract class Person
{
    public  string OIB { get; set; }
    
    public string Name { get; set; }
    
    public  DateTime Date{ get; set; }
    
    public  Gender Gender{ get; set; }

    public Person() { }
    protected Person(string oIB, string name, Gender gender, DateTime date)
    {
        OIB = oIB;
        Name = name;
        Date = date;
        Gender = gender;
    }
}
dbc
  • 104,963
  • 20
  • 228
  • 340

1 Answers1

1

The generic Serialize<T> method serializes the object as the type T, if you assigned the instance to its parent type variable, only the properties in parent class will be serialized.

Person person = new Student();
Serialize<Person>(filePath, person);

Try to explicitly tell the type to the serializer.

public static void Serialize(string filePath, object data)
{
    var jsonString = JsonSerializer.Serialize(data, data.GetType());
    ....
}
shingo
  • 18,436
  • 5
  • 23
  • 42