0

I am trying to use System.Text.Json library for performance improvement. When I am trying to convert it, System.Text.Json is not able to deserialize the object but Newtonsoft.Json able to do so.

How to fix it for System.Text.Json?

fiddle https://dotnetfiddle.net/Ukzw6h

using System;
using System.Text.Json;
using Newtonsoft.Json;

public class Person {
    public string Name;
    public string Role;
}
                    
public class Program
{
    public static void Main()
    {
    
        string json = """{"Name":"John","Role":"Software Engineer"}""";
        
        using JsonDocument doc = JsonDocument.Parse(json);
        JsonElement jsonElement = doc.RootElement;
        var personText = System.Text.Json.JsonSerializer.Deserialize<Person>(jsonElement.GetRawText());
        Console.WriteLine($"from System.Text.Json {personText.Role}");
        
        var personNewton = JsonConvert.DeserializeObject<Person>(jsonElement.GetRawText());
        Console.WriteLine($"from Newtonsoft.Json {personNewton.Role}");

    }
}

output:

from System.Text.Json 
from Newtonsoft.Json Software Engineer
4
  • 5
    Make Name and Role properties in the Person class. Commented Jun 12 at 13:36
  • 3
    Or, mark them with the [JsonInclude] attribute. Commented Jun 12 at 13:40
  • 3
    See also Migrate from Newtonsoft.Json - Public and non-public fields Commented Jun 12 at 13:44
  • Use records, see fiddle. Commented Jun 12 at 14:06

1 Answer 1

1

For System.Text.Json these are your options, give them a try:

public class Person {
  [JsonInclude] public string Name;
  public string Role { get; set; }
}

and credit to @fildor in the comments for adding

// Same thing works for Deserialize
JsonSerializer.Serialize(person, new JsonSerializerOptions() { IncludeFields = true });
Sign up to request clarification or add additional context in comments.

2 Comments

That's missing the most obvious JsonSerializerOptions.IncludeFields Property
Particularly if you're not the author of Person. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.