我有这样的东西:
this.router.navigate(['/login']);
我已使用
将数据写入JSON格式的文件中public class MyClass_T
{
public string filename;
public string filename_txt;
public int version = 1;
public double A;
public double B;
....and so on with about 100 more variables
}
现在我想反序列化它。我知道我可以做到:
public bool readFormatFile(string filename)
{
JsonSerializer serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
using (FileStream fs = new FileStream(filename, FileMode.Create, System.IO.FileAccess.Write, FileShare.Read))
{
using (StreamWriter sw = new StreamWriter(fs))
{
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, this);
}
}
}
}
请注意,readFormatFile和writeFormatFile是MyClass_T的一部分。我需要将值返回到我的局部变量中,而不必做一堆
public bool writeFormatFile(string filename)
{
MyClass_T MC = new MyClass_T();
using (FileStream fs = new FileStream(filename, FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
JsonSerializer serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
MC = (MyClass_T)serializer.Deserialize(sr, typeof(MyClass_T));
}
}
}
有关如何进行此操作的想法和想法?
答案 0 :(得分:0)
就像许多人已经明确指出的那样,将JSON对象反序列化为局部变量并不是一个好主意,但是,如果您不能为该对象创建类,则可以使用dynamic
对象类型,这将使您可以将JSON反序列化为对象,而无需添加任何强类型模型/类。
您需要做的就是将反序列化的结果强制转换为dynamic
,就像处理其他任何对象一样,例如
dynamic myObject = (dynamic)serializer.Deserialize(sr, typeof(dynamic));
这将允许您像访问其他任何对象一样访问myObject
myObject.filename
。
我也想重申一下,您确实应该为此使用类,因为它通常会使代码更加可预测,可维护且更干净
答案 1 :(得分:0)
除了使用实例“ ReadFormatFile”方法,您还可以向“ MyClass_T”类添加静态方法“ ReadFormatFile”,该类返回从序列化程序返回的“ MyClass_T”实例。然后,您可以使用该方法来代替调用“ ReadFormatFile”方法(或使用“ new”来实例化一个“ MyClass_T”实例,该实例填充有先前序列化到该文件的信息)。
请考虑以下课程:
class Demo
{
public double A;
public double B;
public void WriteFormatFile(string filename)
{
JsonSerializer serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
using (FileStream fs = new FileStream(filename, FileMode.Create, System.IO.FileAccess.Write, FileShare.Read))
{
using (StreamWriter sw = new StreamWriter(fs))
{
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, this);
}
}
}
}
public static Demo ReadFormatFile(string filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
JsonSerializer serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
return (Demo)serializer.Deserialize(sr, typeof(Demo));
}
}
}
}
及其在其他地方的用途:
const string filename = "demo.json";
var d = new Demo();
d.A = 2;
d.B = 3;
d.WriteFormatFile(filename);
d.A = 4;
// replace d.ReadFormatFile(filename); with the following line
d = Demo.ReadFormatFile(filename);
Console.WriteLine(d.A);
输出将为“ 2”,即“ A”字段的还原值。