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 searilize 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"**}]
CodePudding user response:
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());
....
}
CodePudding user response:
Person Class:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace TxtToXmlParser.Model
{
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;
}
}
}
CodePudding user response:
Student class:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Serialization;
namespace TxtToXmlParser.Model
{
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;
}
}
}