[Serializable]
public class Matrix4
{
private double[] m = new double[16];
}
此课程将序列化为:
{"m":[1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,1]}
但是我希望忽略包装类Matrix4,只需将类序列化为:
[1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,1]
该类用于序列化的其他类。我使用DataContractJsonSerializer进行序列化。
答案 0 :(得分:0)
您可以实现这一点但不能使用默认的JSON序列化程序,因为m
是一个属性,是重建Matrix4
非常重要的信息。
考虑Matrix4
有另一个属性说n
的情况,然后在JSON中没有该信息,您将无法重建它。
但是,如果你真的需要这样的东西,那么你必须使用自定义序列化程序对其进行序列化,你可以通过对其进行子类化来实现它们,然后应用自己的转换代码或只是序列化{{ 1}}属性,但不是完整的类。在这种情况下,一个选项是使用Json.NET库 -
m
但是,您应该知道,您尝试创建的JSON不是基于类var matrix = new Matrix4();
string output = JsonConvert.SerializeObject(matrix.m);
答案 1 :(得分:0)
我猜你误解了serialziation的概念,你只需要创建一个代表m
对象的字符串。为此,您可以使用:
class Matrix4
{
private double[] m;
public Matrix4(double [] pm)
{
this.m = pm;
}
public string GetStringRepresentation()
{
string _RetValue = "[";
for(int i=0;i<this.m.Length;i++)
{
_RetValue += this.m[i];
if(this.m.Length != i)
{
_RetValue += ",";
}
}
_RetValue += "]";
return _RetValue;
}
// your additional functions in here
}
之后,当你使用
时Matrix4 _Matrix = new Matrix4(new double[] { 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0 } );
string _Representation - _Matrix.GetStringRepresentation();
// _Representation = "[1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0]";
如果你真的想序列化,你不要'发明'你自己的格式,你只需让编译器序列化/反序列化对象而不关心它包含什么。