How to save/restore serializable object to/from file?

前端 未结 6 879
旧时难觅i
旧时难觅i 2020-11-22 11:17

I have a list of objects and I need to save that somewhere in my computer. I have read some forums and I know that the object has to be Serializable. But it wou

6条回答
  •  一个人的身影
    2020-11-22 12:07

    1. Restore Object From File

    From Here you can deserialize an object from file in two way.

    Solution-1: Read file into a string and deserialize JSON to a type

    string json = File.ReadAllText(@"c:\myObj.json");
    MyObject myObj = JsonConvert.DeserializeObject(json);
    

    Solution-2: Deserialize JSON directly from a file

    using (StreamReader file = File.OpenText(@"c:\myObj.json"))
    {
        JsonSerializer serializer = new JsonSerializer();
        MyObject myObj2 = (MyObject)serializer.Deserialize(file, typeof(MyObject));
    }
    

    2. Save Object To File

    from here you can serialize an object to file in two way.

    Solution-1: Serialize JSON to a string and then write string to a file

    string json = JsonConvert.SerializeObject(myObj);
    File.WriteAllText(@"c:\myObj.json", json);
    

    Solution-2: Serialize JSON directly to a file

    using (StreamWriter file = File.CreateText(@"c:\myObj.json"))
    {
        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(file, myObj);
    }
    

    3. Extra

    You can download Newtonsoft.Json from NuGet by following command

    Install-Package Newtonsoft.Json
    

提交回复
热议问题