0

I have this class for settings in my console app. When i read the json file, it reads the StopBits as 2 (as expected). But when i then read Console.WriteLine(settings.ServerSettings.StopBits.ToString()); The StopBits is printed as One (not Two/2) What am i doing wrong here when i read the json to my class?

    // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
using System.IO.Ports;
using System.Reflection;
using System.Text.Json.Serialization;
namespace Settings
{

public class ClsSettings
{
    [JsonInclude]
    public ComSettings ClientSettings = new();
    [JsonInclude]
    public ComSettings ServerSettings = new();

}

public class ComSettings
{

    [JsonInclude]
    public string ComSelection { get; set; } = "";
    [JsonInclude]
    public string ComDeviceID { get; set; } = "";
    [JsonInclude]
    public Int32 BaudRate = 9600;
    [JsonInclude]
    public Parity ComParity = Parity.None;
    [JsonInclude]
    public StopBits StopBits = StopBits.One;
    [JsonInclude]
    public int Datasize = 8;

}

}

and the JSon

{
  "ClientSettings": {
    "ComSelection": "",
    "ComDeviceID": "",
    "BaudRate": 9600,
    "ComParity": 0,
    "StopBits": 1,
    "Datasize": 8
  },
  "ServerSettings": {
    "ComSelection": "",
    "ComDeviceID": "",
    "BaudRate": 9600,
    "ComParity": 0,
    "StopBits": 2,
    "Datasize": 8
  }
}
  • 2
    `Root` is missing from your question, though it seems like `ClsSettings` should be used instead of `Root`. – ProgrammingLlama Jun 27 '23 at 09:59
  • 1
    Is there a particular reason why those are fields and not properties and why you mark everything with JsonInclude? – Fildor Jun 27 '23 at 09:59
  • @Fildor-standswithMods: According to another post about json being null/empty, someone commented that that attribute has to be there, [link](https://stackoverflow.com/questions/62717934/c-sharp-jsonserializer-serialize-returns-an-empty-object)for the json to actually take the values from the class – Stefan Grönberg Jun 27 '23 at 10:42
  • It doesn't if it is a public property with get and set. It's the first part of that answer. – Fildor Jun 27 '23 at 11:20

0 Answers0