0

我正在使用 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;

但这没有任何区别。

4

1 回答 1

1

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

[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

这样,序列化程序将只序列化相关井的名称。

于 2013-01-29T00:30:31.793 回答