JSON.Net Collection在默认构造函数中初始化,不会从反序列化的JSON中覆盖

时间:2016-12-03 15:21:15

标签: c# json json.net

我有一个将集合初始化为默认状态的类。当我从一些保存的JSON加载对象时,它会附加值而不是覆盖集合。有没有办法让JSON.Net在反序列化时替换集合而不是附加值?

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;
}

1 个答案:

答案 0 :(得分:3)

是。将ObjectCreationHandling设置为Replace。默认值为Auto

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

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

小提琴:https://dotnetfiddle.net/aBZiim