Search code examples
c#jsonjsonserializer

How to serialize a list of objects of a class that contains a list of a struct


I have a list of objects of a class that is composed of simple properties and a property that is a list of a struct

struct UGdata
{
    public int ID;
    public float curGen;
    public float nomGen;
}
internal class PlantData
{
    public float Level {get;set;}
    public string UGName {get;set;}
    public List<UGData> UGs {get;set;}
}

Inside my code i fill data with sqlserver informations i have something like this:

List<PlantData> MyData = new List<PlantData>
for(int i=0; i<n; i++)
{    
     PlantData info = new PlantData();
     for(int j=0; j<m;j++)
     {
        UGData data = new UGData();
        //fill the UG data properties
        info.UGs.Add(data)
        //fill other info properties
     }
     MyData.Add(info)
}

And in the end i want serialize these informations: (I'm using System.Texts.Json)

string Jsonoutput = JsonSerializer.Serialize(MyData)

The output come from without struct informations, like this:

{
    "Level":10
    "UGName":A
    "UGs": []
},
{
    "Level":30
    "UGName":B
    "UGs": []
}

I have to write a specific Serializer for this structure? I read some threads with similar options but I couldn't make any progress. Any ideas? Thanks a lot!


Solution

  • System.Text.Json does not serialize fields by default. You need either to use properties:

    struct UGdata
    {
        public int ID { get; set; }
        public float curGen { get; set; }
        public float nomGen { get; set; }
    }
    

    Or include fields explicitly either via serializer options:

    string jsonOutput = JsonSerializer.Serialize("MyData", new JsonSerializerOptions
    {
        IncludeFields = true
    });
    

    Or by marking fields with corresponding attribute.

    struct UGdata
    {
        [JsonInclude]
        public int ID;
        [JsonInclude]
        public float curGen;
        [JsonInclude]
        public float nomGen;
    }