Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.Net Collection initialized in default constructor not overwritten from deserialized JSON

Tags:

json

c#

json.net

I have a class that initializes a collection to a default state. When I load the object from some saved JSON it appends the values rather than overwriting the collection. Is there a way to have the JSON.Net replace the collection when deserializing rather than append the 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;
}
like image 423
Brad Patton Avatar asked Dec 03 '16 15:12

Brad Patton


1 Answers

Yes. Set the ObjectCreationHandling setting to Replace. The default is Auto.

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

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

Fiddle: https://dotnetfiddle.net/aBZiim

like image 103
Brian Rogers Avatar answered Oct 01 '22 01:10

Brian Rogers