The JSON.Net collection, initialized in the default constructor, not overwritten by deserialized JSON

I have a class that initializes the collection to its default state. When I load an object from some stored JSON, it adds values, not overwrites the collection. Is there a way for JSON.Net to replace the collection during deserialization rather than adding values?

void Main() {
    string probMatrix = "{\"Threshold\":0.0276,\"Matrix\":[[-8.9,23.1,4.5],[7.9,2.4,4.5],[9.4,1.4,6.3]]}";
    var probabiltyMatrix = JsonConvert.DeserializeObject<ProbabiltyMatrix>(probMatrix);
    probabiltyMatrix.Dump();
}

// Define other methods and classes here
public class ProbabiltyMatrix {

    public ProbabiltyMatrix() {
        // Initialize the probabilty matrix
        Matrix = new List<double[]>();
        var matrixSize = 3;
        for (var i = 0; i < matrixSize; i++) {
            var probArray = new double[matrixSize];
            for (var j = 0; j < matrixSize; j++) {
                probArray[j] = 0.0;
            }
        Matrix.Add(probArray);
        }
    }

    public double Threshold;
    public List<double[]> Matrix;
}
+4
source share
1 answer

Yes. Set the ObjectCreationHandlingvalue Replace, the default is used Auto.

var settings = new JsonSerializerSettings();
settings.ObjectCreationHandling = ObjectCreationHandling.Replace;

var probabiltyMatrix = JsonConvert.DeserializeObject<ProbabiltyMatrix>(probMatrix, settings);

Fiddle: https://dotnetfiddle.net/aBZiim

+3
source

Source: https://habr.com/ru/post/1662730/


All Articles