c# - 使用 json 序列化(反)序列化多个对象时出现 Null 问题

标签 c# json serialization deserialization

[已解决]应用给定的解决方案,工作正常!

程序的目的:当用户打开和关闭程序时保存/重新加载以前的数据。

我曾经使用一个对象(obj)成功(反)序列化,现在我有两个不同类的不同对象。

我尝试通过查看其他帖子来将它们结合起来;我将它们放入对象数组中,并在(反)序列化作为参数时给出该对象数组。

I do initialize for example like this; obj.flag1 = true; before calling serialize() in other methods.(I didn't put them for simplicity since I already stated the functionality of methods)

它说对象为空,但从逻辑上讲,如果 obj2 和 obj 为空,则应该给出 obj 独立的错误。它不会读取我处理过的空文件。当我尝试组合两个对象时,它开始给我两个对象带来空错误。我快要扯头发了,有人可以帮忙吗?

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

        }

String values are in this class via "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(){

        }
    }

Boolean values are in this class via "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()
        { 

        }

    }

warning of null objects

最佳答案

您要反序列化的位置:-

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

您要求反序列化器返回一个数组原始对象,这将产生一个 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; }
}

关于c# - 使用 json 序列化(反)序列化多个对象时出现 Null 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57408086/

相关文章:

json - 为什么 Kotlin Object 类到 json 对象为 null?

c# - 使用语言代码 (en) 还是完整的文化代码(例如 en-AU)?

c# - Gridview 排序后自动选择第一行

C# 通过 Process.Exited 发送参数

javascript - 如何迭代 json 对象的嵌套属性并创建新的数组列表?

java - gson.toGson() 不调用自定义序列化方法

c# - ASP.NET 中的大 ViewState 值

android - 使用 Volley 发布 JsonObject

json - 如何将字典转换为不带空格和换行符的json字符串

c# - 为什么 BinaryFormatter 试图在可序列化类上序列化事件?