串行化时避免扩展链接对象

时间:2013-01-28 23:11:40

标签: c# .net json json.net

我正在使用JSON.NET将一些c#对象序列化为JSON(然后写入文件)。

我的两个主要课程是:

public class Reservoir {
    private Well[] mWells;

    public Well[] wells {
        get { return mWells; }
        set { mWells = value; }
    }
}

public Well() {
    private string mWellName;
    private double mY;
    private double mX;

    public string wellName {
        get { return mWellName; }
        set { mWellName = value; }
    }


    public double y {
        get { return mY; }
        set { mY = value; }
    }

    public double x {
        get { return mX; }
        set { mX = value; }
    }

    private Well[] mWellCorrelations;
}

问题是输出如下:

'{"wells":[{"wellName":"B-B10","y":217.04646503367468,"x":469.5776343820333,"wellCorrelations":[{"wellName":"B-B12","y":152.71005958395972,"x":459.02158140110026,"wellCorrelations":[{"wellName":"B-B13","y":475.0,"x":495.14804408905263,"wellCorrelations":[{"wellName":"B-B11","y":25.0,"x":50.0,"wellCorrelations":[]}

即。每个井对象的相关井作为物体本身扩展,当存在大量相关物体时,这成为空间和时间的严重问题。

我想我会更喜欢这样的东西:

'{"wells":[{"wellName":"B-B10","y":217.04646503367468,"x":469.5776343820333,"wellCorrelations":[{"wellName":"B-B12"}], {"wellName":"B-B11","y":217.04646503367468,"x":469.5776343820333,"wellCorrelations":[{"wellName":"B-B13"}

即仅将井名维护为链接(假设其​​唯一)。

有没有办法用JSON.NET做到这一点?

您已设置

serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

但它没有任何区别。

1 个答案:

答案 0 :(得分:1)

您可以添加一个名为WellCorrelations的新readonly属性,该属性只获取井相关的名称,并在mWellCorrelations上打一个JsonIngore属性,如下所示:

[JsonIgnore]
private Well[] mWellCorrelations;

public string[] WellCorrelations 
{ 
    get { return mWellCorrelations.Select(w => w.wellName).ToArray(); }
}

http://james.newtonking.com/projects/json/help/html/ReducingSerializedJSONSize.htm

这样,序列化器只会序列化相关孔的名称。