簡體   English   中英

使用json(反序列化)多個對象時出現空問題

[英]Null problem when (de)serializing multiple objects with json

[解決]應用了給定的解決方案,效果很好!

該程序的目的:當用戶打開和關閉該程序時,保存/重新加載以前的數據。

我曾經使用一個對象obj成功地對(反)序列化,現在我有兩個不同類的不同對象。

我試圖通過查看其他帖子將它們組合在一起; 我將它們放在對象數組中,並在將(反)序列化為參數時提供該對象數組。

我確實像這樣初始化。 obj.flag1 = true; 在其他方法中調用serialize()之前。(因為我已經說明了方法的功能,所以我沒有為了簡單起見就把它們放進去)

它說對象為空,但是從邏輯上講,如果obj2和obj為空,則應該為obj獨立給出錯誤。 它不會讀取我處理過的空文件。 當我嘗試組合兩個對象的那一刻開始,這兩個對象都給了我null錯誤。 我將要扯頭發,有人可以幫忙嗎?

 [Serializable]
    public partial class UI : Form
    {
        FlagClass obj;
        CurrentAmplitude obj2;

        object[] seri_obj;//combine multiple objects

        //deserialization is performed in constructor
        public UI()
        {

            InitializeComponent();

            seri_obj = new object[] { obj, obj2 };

            input += ".txt";

            //default path + new filename
            path_combined = Path.Combine(root, input);

            //it won't try to read empty file
            if (!File.Exists(path_combined))
            {

                using (var stream = File.Create(path_combined))
                {

                }

            }
            else //already have that file,so when user opens the program, data is loaded from file
            {
                //read booleans and inetegres

                string json2 = File.ReadAllText(path_combined);
                string FormattedJson = FormatJson(json2);
                seri_obj = JsonConvert.DeserializeObject<object[]>(FormattedJson);

            }
        }


        private static string FormatJson(string json)
        {
            dynamic parsedJson = JsonConvert.DeserializeObject(json);
            return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
        }

        //I do serialization here
        void Serialize()
        {
            string json = JsonConvert.SerializeObject(seri_obj, Formatting.Indented);
            File.WriteAllText(path_combined, json);

        }

字符串值通過“ obj2”在此類中

[Serializable]
    class CurrentAmplitude
    {
    //this class has the string values
        [JsonProperty(PropertyName = "value1")]
        public int value1 { get; set; }

        [JsonProperty(PropertyName = "value2")]
        public string value2 { get; set; }

        [JsonProperty(PropertyName = "value3")]
        public string value3 { get; set; }

        [JsonProperty(PropertyName = "value4")]
        public string value4 { get; set; }

        [JsonProperty(PropertyName = "value5")]
        public string value5 { get; set; }


        public CurrentAmplitude(){

        }
    }

布爾值通過“ obj”在此類中

[Serializable]
    class FlagClass
    {
    //this class has the boolean values
        [JsonProperty(PropertyName = "flag1")]
        public bool flag1 { get; set; }

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

        public FlagClass()
        { 

        }

    }

空對象警告

在反序列化的地方:

seri_obj = JsonConvert.DeserializeObject<object[]>(FormattedJson);

JObject解串器返回一個數組原始對象,這將導致一個JObject類型的數組,而不是FlagClassCurrentAmplitude類型。

您還要設置seri_obj ,但不要將seri_obj的值分配給objobj2變量,這就是編譯器警告您的原因。

您最好擁有這樣的傘形配置類:-

class Configuration
{
    public Flag { get; set; } = new FlagClass();

    public CurrentAmplitude { get; set; } = new CurrentAmplitude();
}

然后,當您要加載/保存時,只需反序列化/序列化Configuration類的實例即可。

// create config object if new
var config = new Configuration();

// to save
var json = JsonConvert.SerializeObject(config);

// to load
var config = JsonConvert.DeserializeObject<Configuration>(json);

// get/set config values
config.Flag.flag2 = false;

這是一個更完整的示例:

void Main()
{
    // create a new blank configuration
    Configuration config = new Configuration();

    // make changes to the configuration
    config.CurrentAmplitude.value1 = 123;
    config.CurrentAmplitude.value2 = "Hello";
    config.FlagClass.flag1 = false;
    config.FlagClass.flag2 = true;

    // serialize configuration to a string in order to save to a file
    string json = JsonConvert.SerializeObject(config);

    // reload config from saved string
    config = JsonConvert.DeserializeObject<Configuration>(json);

    // should print "Hello"
    Console.WriteLine(config.CurrentAmplitude.value2);
}

class Configuration
{
    public CurrentAmplitude CurrentAmplitude { get; set; } = new CurrentAmplitude();

    public FlagClass FlagClass { get; set; } = new FlagClass();
}

class CurrentAmplitude
{
    public int value1 { get; set; }

    public string value2 { get; set; }

    public string value3 { get; set; }

    public string value4 { get; set; }

    public string value5 { get; set; }
}

class FlagClass
{
    public bool flag1 { get; set; }

    public bool flag2 { get; set; }
}

在C#6之前的版本中,您的配置類如下所示:

class Configuration
{
    public Configuration()
    {
        CurrentAmplitude = new CurrentAmplitude();
        FlagClass = new FlagClass();
    }

    public CurrentAmplitude CurrentAmplitude { get; set; }

    public FlagClass FlagClass { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM