0

Trying to deserialize a simple JSON string to a Rules object in .NET Core 3.1

using System.Text.Json;

namespace Whatever
{
  public class Rules
  {
    public SyncResponse SyncResponse;

    public Rules Load() 
    {
      var text = File.ReadAllText("/path/to/json.txt");
      var options = new JsonSerializerOptions 
      { 
        PropertyNameCaseInsensitive = true, 
        ReadCommentHandling = JsonCommentHandling.Skip 
      };

      var result = JsonSerializer.Deserialize<Rules>(text, options);
      return result;
    }
  }

  public class SyncResponse
  {
    public string Status;
  }
}

The content of the JSON file looks as follows

/* Some comment here */
{"SyncResponse":{"status":"success"}}

However; when I call Rules.Load(), it returns an instance of Rules, but SyncResponse is null. Can anyone point out what I'm doing wrong?

dbc
  • 104,963
  • 20
  • 228
  • 340
KBoek
  • 5,794
  • 5
  • 32
  • 49
  • 3
    Try making your fields properties (e.g. `public string Status { get; set; }` – Martin Costello May 19 '20 at 14:09
  • Thanks @MartinCostello, that was the solution! Mind to write that as an answer; so that I can upvote it? – KBoek May 19 '20 at 14:15
  • 3
    Currently `System.Text.Json` [ignores a fields](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#serialization-behavior), this is a main point here – Pavel Anikhouski May 19 '20 at 14:21

0 Answers0