【问题标题】:Serialization problem while saving json string to txt file将json字符串保存到txt文件时的序列化问题
【发布时间】: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


【解决方案1】:

您的 FormatJson 方法并没有完全完成任何事情,原因有两个(我可以看到)。

  1. 您在调用FormatJson 的两个地方都完全忽略了返回的字符串,并且从不将其分配给字符串变量。
  2. 您实际上只是在反序列化然后重新序列化,只是稍后再次反序列化。没有真正的原因。

你至少可以通过做一个小小的改变来开始获得结果。在您注释的//flag situation 代码块中,您可以简单地实例化一个string 变量并将FormatJson 的返回值分配给它。然后,将其反序列化为您的 FlagClass 对象。

if (!File.Exists(path_combined)) {
    using(var stream = File.Create(path_combined)) {
        //flag situation
        string json2 = File.ReadAllText(path_combined);
        string FormattedJson = FormatJson(json2);
        obj = JsonConvert.DeserializeObject < FlagClass > (FormattedJson);
    }
}
else {
    //flag situation
    string json2 = File.ReadAllText(path_combined);
    string FormattedJson = FormatJson(json2);
    obj = JsonConvert.DeserializeObject < FlagClass > (FormattedJson);
}

【讨论】:

  • 我应用了你的解决方案,但它没有用,我的代码甚至没有序列化,我看不到 txt 文件的变化。你还有什么建议吗? :(
  • 我建议逐步使用断点并调试程序的每一步。您正在尝试读取文件的内容,但是我的答案中包含的第一个 if 语句询问该文件是否存在。如果没有,您正在创建它,然后尝试将其内容读取到json2。此时,您的文件不应具有 任何内容,因此无法反序列化,这将导致没有任何内容显示给您。那有意义吗?我可能解释得不够清楚。
  • 我再次追踪,我在创建文件后删除了反序列化,现在它只是创建,否则(文件存在)进行反序列化。我还检查了我的序列化,我在我的void Serialize() 方法中的“json”处设置了一个断点,我点击了按钮,意味着我更改了标志,但是 json 字符串看起来仍然为空,我试图找出原因
  • 另一个好问题可能是...您的flag 属性是否曾经设置为true 表示false?您将 NullHandling 设置为 Ignore,因此如果 bool 属性只是 null,那么它可能永远不会通过这些序列化程序设置写入 json。
  • @Specvaucs 我发现了我的问题,它不是原始代码,我通过线程更改我的标志,在线程完成任务之前,序列化尝试读取,返回 false,所以为了解决我必须阅读内部线程并且必须使用 Invoke,因为线程无法看到外部主线程,谢谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 2012-04-14
  • 1970-01-01
相关资源
最近更新 更多