是否可以序列化类,例如:
public static class Foo
{
public static int foo1 = 1;
public static int foo2 = 2;
public static string foo3 = "test";
}
使用C#中的JsonSerializer进入JSON?
如果我使用:
JsonWriter jw = new JsonTextWriter(streamWriter)
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, Foo);
出现错误:
error CS0118: 'Example.Foo' is a 'type' but is used like a 'variable'
提前感谢任何回复。
@Update 序列化静态classess是不可能的,但您可以创建此类的静态实例并对其进行序列化。 样品:
public static FooClass Foo = new FooClass();
[Serializable]
public class FooClass : System.Runtime.Serialization.ISerializable
{
public FooClass()
{
}
public static int foo1 = 1;
public static int foo2 = 2;
public static string foo3 = "test";
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("static.foo1", FooClass.foo1, typeof(int));
info.AddValue("static.foo2", FooClass.foo2, typeof(int));
info.AddValue("static.foo3", FooClass.foo3, typeof(string));
}
public FooClass(SerializationInfo info, StreamingContext context)
{
FooClass.foo1 = info.GetInt32("static.foo1");
FooClass.foo2 = info.GetInt32("static.foo2");
FooClass.foo3 = info.GetString("static.foo3");
}
}
...
serializer.Serialize(jw, Foo);
答案 0 :(得分:2)
或者,如果您不想实现所有序列化垃圾,您只需序列化一个匿名类型:
JsonWriter jw = new JsonTextWriter(streamWriter)
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw,
new {
foo1 = Foo.foo1,
foo2 = Foo.foo2,
foo3 = Foo.foo3
});