序列化时避免展开链接对象
本文关键字:链接 对象 序列化 | 更新日期: 2023-09-27 17:56:29
我正在使用 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;
但这没有任何区别。
您可以添加一个名为 WellCorrelations 的新只读属性,该属性仅获取井相关性的名称,并在 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
这样,序列化程序将仅序列化相关井的名称。