JsonConvert.Deserialize appends to default property values. How to prevent this?

newtonsoft json deserialize null
newtonsoft json serialize ignore property runtime
newtonsoft json deserialize default value
jsonserializersettings
newtonsoft json ignore empty string
json.net deserialize empty string to null
jsonconvert.serializeobject ignore property
jsonconvert.serializeobject missing properties

I have a .json config file in which I store application settings which are deserialized when the app starts.

Example:

{
    "MyProperty1": "MyValue1",
    "MyProperty2": [1, 2, 3]
}

The object to which the JSON is deserialized is:

public class Config{
    public string MyProperty1{ get; set; }
    public List<int> MyProperty2{ get; set; } = new List<int> { 4, 5, 6 };
}

The problem I am having is that, when the JSON for the property MyProperty2 is deserialized, it appends the values 1, 2, 3 to the default property values 4, 5, 6 and the result is that MyProperty2 = 4, 5, 6, 1, 2, 3

I'd like MyProperty2 to DEFAULT to 4, 5, 6 unless otherwise specified in the .json config file. Any help would be appreciated, thanks.

try to solve everything inside the Config class:

public class Config
{
    public Config()
    {
        this.MyProperty2 = new List<int> { 4, 5, 6 };
    }
    public string MyProperty1 { get; set; }
    public List<int> MyProperty2 {
        get {
            return this.MyProperty2;
        } 
        set {
            if(this.MyProperty2.Count > 0)
            {
                this.MyProperty2.Clear();
                this.MyProperty2 = value;
            }
        } 
    }
}

Reducing Serialized JSON Size, If a class has many properties and you only want to serialize a small subset of Json.NET also allows you to customize what the default value of an individual� 0 Binding Property to Textbox on Datagrid not showing value after setter routine Feb 1 '19 0 Setting background on IOS Sep 3 '19 0 Choosing the default value of an Enum type without having to change values Jan 9 '19

This usually works for me: You may think that if a 'get' request is made it will set the default value. If a 'set' is done before the 'get' the property will only get the default value if the 'value' is null.

public class Config{
    public string MyProperty1{ get; set; }

    private List<int> myProperty2{ get; set; } ;
    public List<int> MyProperty2{ 
        get{
            if (myProperty2 == null)
                myProperty2 = new List<int> { 4, 5, 6 };

            return  myProperty2 ;
        } 
        set{
            myProperty2 = value;
        } 
    } 
}

DefaultValueAttribute, DefaultValueAttribute to override the default value for a property and exclude it from serialization using T:Newtonsoft.Json.DefaultValueHandling. This sample uses the T:System.ComponentModel.DefaultValueAttribute to override the default value for a property and exclude it from serialization using T:Newtonsoft.Json.DefaultValueHandling.

You can use JsonConvert of Newtonsoft.Json;

var setting = "{\"MyProperty1\": \"MyValue1\", \"MyProperty2\": [1, 2, 3]}";
var settingConfig = JsonConvert.DeserializeObject(setting);

And Config Class

public class Config
{
    public string MyProperty1 { get; set; }
    [Newtonsoft.Json.JsonConverter(typeof(DefaultArrayConverter))]
    public List<int> MyProperty2 { get; set; } = new List<int> { 4, 5, 6 };
}

Here I wrote a customer JsonConverter.

public class DefaultArrayConverter : JsonConverter
{

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var value = serializer.Deserialize(reader, objectType);
        return value;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return false;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

It is working fine but I am not exactly sure why MyProperty2 has 6 values in your implementation.

NullValueHandling setting, This sample serializes an object to JSON with T:Newtonsoft.Json. NullValueHandling set to Ignore so that properties with a default value aren't included in the� Ignore members where the member value is the same as the member's default value when serializing objects so that it is not written to JSON. This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, decimals and floating point numbers; and false for booleans).

Based on the answer from one of the comments above, and combined with my obsessive compulsive requirement to not leave a question with an unaccepted answer, herewith:

Assuming that the variable json contains the content of the .json configuration file:

var cfg = JsonConvert.DeserializeObject<Config>(json, new JsonSerializerSettings
{
    ObjectCreationHandling = ObjectCreationHandling.Replace
});

The key is the ObjectCreationHandling - the serializer setting ObjectCreationHandling.Replace replaces the default rather than appending to it.

See more here

[PDF] Json.NET, Controls how null values are handled during serialization and By default the JSON property will have the same name as the true to keep object reference; otherwise, false. The name of the root element to append when deserializing. This sample creates a class that inherits from T:Newtonsoft.Json.Converters.CustomCreationConverter`1 that instantiates Employee instances for the Person type.

JSON Serialization Usage, Flexjson is a lightweight library for serializing and deserializing Java objects into and from JSON. By default Flexjson serializes the immediate fields of that object. When an object is serialized the names of the properties on JSON objects are "keys" to the path and the values by appending "values" just like Collections. This sample uses the T:Newtonsoft.Json.JsonIgnoreAttribute to exclude a property from serialization.

Deserialize JSON into C# dynamic object?, Is there a way to deserialize JSON content into a C# 4 dynamic type? It would be Append(","); firstInDictionary = false; var value = pair.Value� By default, the Columns property is set to automatically create the table columns based on the array items. To specify custom headers and values, follow these steps: Open the Columns list, and select Custom. In the Header property, specify the custom header text to use instead. In the Value property, specify the custom value to use instead.

How to remove backslash from json data in C#?, CreateResponse(status, JsonConvert.DeserializeObject(json)); in your code it will add backslash by default, and you can remove it by� JsonConvert.DeserializeObject can leave reference type member properties null during deserialization without [JsonProperty] attribute on the property. Try this: 1. Synchronize the property name in the class and in the JSON file. 2. Add [JsonProperty] attribute to the property in the C# class.

Comments
  • ObjectCreationHandling.Replace is what google returns
  • Heh, I obviously cant use Google (I did try) - indeed that is the answer :) Thank you. If you want the points, post the answer and I'll accept.
  • ObjectCreationHandling.Replace results 1,2,3 after deserialization, not the 4,5,6, as OP wants
  • not the 4,5,6, as OP wants ... I'm pretty sure that is not true as: I'd like MyProperty2 to DEFAULT to 4, 5, 6 unless otherwise specified in the .json config file
  • the only problem it would be { "MyProperty2": null } in json(but then it's still specified in the json)
  • I agree, this is the long way to solve the problem :) However, as @Selvin noted above, using the JsonConvert setting ObjectCreationHandling.Replace will solve the issue I was having.