.NET8 Serialize class as JSON
Hi!
I'm currently working on a graph creation and visualisation app with .NET8. I wanted to serialize separately the graphs fields références and the data to be able to load definitions without opening the large data file. But I have an issue: I have a GraphPoint class which contain every field of a point data as follow:
public class GraphPoint
{
public Dictionary<string, int> integerFields = new Dictionary<string, int>();
public Dictionary<string, float> floatFields = new Dictionary<string, float>();
public Dictionary<string, TimeOnly> timeOnlyFields = new Dictionary<string, TimeOnly>();
public Dictionary<string, DateOnly> dateOnlyFields = new Dictionary<string, DateOnly>();
public Dictionary<string, DateTime> dateTimeFields = new Dictionary<string, DateTime>();
public Dictionary<string, string> stringFields = new Dictionary<string, string>();
public Dictionary<string, bool> boolFields = new Dictionary<string, bool>();
public GraphPoint(GraphType graphModel)
[...]
}
Then, i want to serialize to JSON the "PointsSaveDataFormat" Class which represent a dataSet as follow:
public class PointsSaveDataFormat
{
public string dataSetName { get; set; }
public List<GraphPoint> graphPoints{ get; set;}
public PointsSaveDataFormat()
{
}
public PointsSaveDataFormat(string _dataSetName, List<GraphPoint> _graphPoints)
{
this.dataSetName = _dataSetName;
this.graphPoints = _graphPoints;
}
}
My issue is that i don't understand how to serialize "PointsSaveDataFormat"
Do I just use a stupid method or I need to learn how to Serialize my class?
Thanks in advance for your answers.
5 Replies
Uh, just
...?
that's what i tryed but it create an empty field
Ah, well, you have public fields there
Either make them properties
Or use the serializer settings to serialize fields as well
Cache it in a readonly field
then use it
ok, thanks a lot, I'l try that.
Thanks a lot, I just hadn't found the right JsonSerializerOptions.
Just for the precision, I used:
"jsonSerializerOptions = new(){IncludeFields = true};"
and it work just fine. thanks again.
Ah, right, that's the actual name of this setting
Glad it worked out