12

I have upgraded my version of .Net Core from preview 2 to preview 6 which has broken a couple of things. Most significant is that I cannot use newtonsoft JSON anymore.

AddNewtonsoftJson in ConfigureServices seemingly does nothing, and the new Json serializer seems to work on properties only, not fields. It does not see the JSONIgnoreAttribute.

In ConfigureServices (in Startup) I have the line

services.AddMvc(x => x.EnableEndpointRouting = false).AddNewtonsoftJson();

which doesn't seem to be doing what it should. In my application, only properties are serialized, not fields, and the [JSONIgnore] attribute does nothing.

The lack of fields I can work around by promoting all the public fields I need to be properties, but I need to be able to ignore some.

Has anyone else had this? How do I either get the new JSON serializer to ignore some properties and serialize public fields, or go back to Newtonsoft?

Ahmad Ibrahim
  • 1,915
  • 2
  • 15
  • 32
craig
  • 421
  • 4
  • 13
  • 1
    I have the exact same problem and created an issue on dotnet/core github. For your problem, maybe using `[System.Text.Json.Serialization.JsonIgnore]` could do the trick instead of using Newtonsoft's JsonIgnore attribute – Drewman Aug 28 '19 at 08:53
  • Only method working for me on .net core 3.1 are DataContract/DataMember attributes. See http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size or https://stackoverflow.com/questions/10169648/how-to-exclude-property-from-json-serialization. I'm also using AddNewtonsoftJson() after .AddControllers and JsonIgnore property is ironically being ignored – itzJustKranker Dec 09 '19 at 22:25

1 Answers1

0

System.Text.Json has a JsonIgnore attribute, please see How to ignore properties with System.Text.Json.

In order for it to work you will need to remove the dependency on Newtonsoft.Json and change the namespaces in relevant files to System.Text.Json.Serialization;

Sytem.Text.Json can include fields, but only public ones.

using System.Text.Json;
using System.Text.Json.Serialization;

var json = JsonSerializer.Serialize(new O(), new JsonSerializerOptions() { WriteIndented = true});
Console.WriteLine(json);

class O {
    [JsonInclude]
    public int publicField = 1;

    //[JsonInclude] 
    //This won't work and throws an exception
    //'The non-public property 'privateField' on type 'O' is annotated with 'JsonIncludeAttribute' which is invalid.'
    private int privateField = 2;

    [JsonIgnore]
    public int P1 { get; set;} = 3;

    public int P2 { get; set; } = 4;
}

This results in:

{
  "P2": 4,
  "publicField": 1
}

Alternatively you can use IncludeFields

var json = JsonSerializer.Serialize(new O(), new JsonSerializerOptions() { IncludeFields = true});

(Reference: Include fields)

tymtam
  • 31,798
  • 8
  • 86
  • 126