AddNewtonsoftJson is not overriding System.Text.Json
Asked Answered
F

1

13

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?

Frances answered 27/8, 2019 at 2:46 Comment(2)
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 attributeGulf
Only method working for me on .net core 3.1 are DataContract/DataMember attributes. See james.newtonking.com/archive/2009/10/23/… or #10170148. I'm also using AddNewtonsoftJson() after .AddControllers and JsonIgnore property is ironically being ignoredKleper
E
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)

Evanne answered 28/3, 2022 at 11:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.