【发布时间】:2019-07-25 08:08:06
【问题描述】:
这是我第一次做(反)序列化和 我的代码无法序列化(或者可能是因为反序列化),我的逻辑是:当我打开程序时,构造函数从文本文件中读取先前保存的值。这就是我将反序列化放在那里的原因。并且每当 bool 值发生变化时,我都会立即对其进行序列化。
我阅读了其他问题,这就是我以这种方式进行反序列化的原因。
我检查了问题是否源于 File.WriteAllText(path_combined, json); ,如果文件存在,它会覆盖,它不应该产生问题。
我当前的 txt 文件显示 bool 变量设置为 false 并且不会更改。
这是我执行(反)序列化的 UI 类
[Serializable]
public partial class UI: Form {
string input = Interaction.InputBox("Enter a serial number", "TEST", "Default", -1, -1);
//DEFAULT PATH ROOT
String root = @".\\";
string path_combined;
FlagClass obj;
public UI() {
InitializeComponent();
obj = new FlagClass();
foreach(string s in SerialPort.GetPortNames()) {
cbxPort.Items.Add(s);
cbxPort.SelectedIndex = 0;
}
input += ".txt";
//default path + new filename
path_combined = Path.Combine(root, input);
if (!File.Exists(path_combined)) {
using(var stream = File.Create(path_combined)) {
//if (new FileInfo(path_combined).Length > 0)
//flag situation
string json2 = File.ReadAllText(path_combined);
FormatJson(json2);
obj = JsonConvert.DeserializeObject < FlagClass > (json2);
}
}
else {
//flag situation
string json2 = File.ReadAllText(path_combined);
FormatJson(json2);
obj = JsonConvert.DeserializeObject < FlagClass > (json2);
}
}
private static string FormatJson(string json) {
dynamic parsedJson = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
void Serialize() {
string json = JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
File.WriteAllText(path_combined, json);
}
private void btn_test1_Click(object sender, EventArgs e) {
obj.flag = true;
Serialize();
}
}
这是我下面的标志类:
[Serializable]
class FlagClass {
//command flags
[JsonProperty(PropertyName = "flag")]
public bool flag {
get;
set;
}
public FlagClass() {
}
【问题讨论】:
-
您的问题到底是什么?你调试过这段代码吗?你知道
FormatJson(json2);真的什么都没做吗? -
@AFriend 我的 json 看起来为空,但它应该给出一个错误,为什么我的 json2 什么都不做,你知道吗?
-
您忽略了来自
FormatJson的返回值。如果你没有向文件中写入任何内容,那么当你反序列化内容时,你会得到一个空的 JSON 对象。 -
@AFriend 这是我第一次尝试序列化,我很难理解,我如何忽略 FormatJson?正如我所说,它将默认布尔标志写入 txt 文件
标签: c# json serialization deserialization