我使用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;
但这并没有什么不同。
发布于 2013-01-29 00:30:32
您可以添加一个名为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
这样,序列化程序将只序列化相关油井的名称。
https://stackoverflow.com/questions/14572982
复制相似问题