0

it is my first time doing (de)serialization and my code fails to serialize(or maybe because of the deserialize), my logic is: When I open the program, constructor reads the previously saved values from text file. That is why I put deserialization there. And whenever a bool value is changed, I immediately serialize it.

I read other questions that is why I did my deseriazliation in this way.

I checked if the problem stems from File.WriteAllText(path_combined, json); , it overwrites if file exists, it shouldn't create problem.

My current txt file show the bool variables set to false and won't change.

This is my UI class where I perform (de)serialization

[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();
    }

}

And this is my flag class below:

[Serializable]
class FlagClass {
    //command flags

    [JsonProperty(PropertyName = "flag")]
    public bool flag {
        get;
        set;
    }

    public FlagClass() {

}
4
  • 2
    What exactly is your problem? Have you debugged this code? Are you aware that FormatJson(json2); isn't really doing anything? Commented Jul 25, 2019 at 8:14
  • @AFriend my json looks null but it should have give an error for that, why my json2 does nothing, do you have any idea? Commented Jul 25, 2019 at 8:30
  • 1
    You ignore the returned value from FormatJson. And if you didn't write anything to the file, then you get an empty JSON object back when you deserialise the contents. Commented Jul 25, 2019 at 8:37
  • @AFriend it is my fist time trying to serialize, I am struggling to understand, how I ignore FormatJson? And as I stated, it writes default boolean flag to txt file Commented Jul 25, 2019 at 8:41

1 Answer 1

1

Your FormatJson method doesn't exactly accomplish anything, for two reasons (that I can see.)

  1. You completely ignore the returned string in both places where you call FormatJson, and never assign it to a string variable.
  2. You're essentially just deserializing then reserializing, only to deserialize again later. There's no real reason for this.

You can at least start to get results by making one small change. Inside of your commented //flag situation code blocks, you can simply instantiate a string variable and assign the return value of FormatJson to it. Then, deserialize that to your FlagClass object.

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

I applied your solution but it did't work, my code does not even serialize, I can not see the change in txt file. Do you have any other suggestion? :(
I would recommend stepping through using breakpoints and debugging your program every step of the way. You're attempting to read in a file's contents, however the first if statement included in my answer asks if the file exists or not. If it doesn't, you're creating it, then attempting to read its contents to json2. At that point, your file shouldn't have any contents, so it's impossible to deserialize, which results in nothing being displayed for you. Does that make sense? I may not have explained that well enough.
I traced again, I delete the deserialization after creating file, now it just creates, else(file exists) does the deserialization. I checked my serialization also, I put a breakpoint at "json" in my void Serialize() method, I clicked button, means I changed the flag, however json string still looks null, I am trying to figure out why
Another good question might be... Is your flag property ever set to true for false? You have NullHandling set to Ignore, so if that bool property is just null then it may never be written to a json through those serializer settings.
@Specvaucs I found my problem, it is not the original code, I change my flag through threads, before thread complete its duty, serialize try to read, returns false, so in order to solve that I have to read inside thread and must use Invoke since threads can not see outside main thread, thank you for your help
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.