简体   繁体   English

在 C# 中使用 JSON 动态序列化和反序列化

[英]Serializing and Deserializing dynamically using JSON in C#

First of all, I think I am trying to serialize and deserialize dynamically, not programmatically.首先,我想我正在尝试动态序列化和反序列化,而不是以编程方式。 Sorry if I made a mistake in the title.对不起,如果我在标题中犯了错误。

I am a Software Engineering student, and I am trying to learn a bit about JSON.我是一名软件工程专业的学生,​​我正在努力学习一些关于 JSON 的知识。 I created a class (I will probably use it as .dll for my projects) to serialize and deserialize.我创建了一个类(我可能会将它用作我的项目的 .dll)来序列化和反序列化。

    public class JSONParser
    {
        public object JsonDeserialize(Type dataType, string filePath)
        {
            JsonSerializer jsonSerializer = new JsonSerializer();

            StreamReader sr = new StreamReader(filePath);
            JsonReader jsonReader = new JsonTextReader(sr);
            JObject obj = jsonSerializer.Deserialize(jsonReader) as JObject;

            jsonReader.Close();
            sr.Close();

            return obj.ToObject(dataType);
        }

        public void JsonSerialize(object data, string filePath)
        {
            JsonSerializer jsonSerializer = new JsonSerializer();

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            StreamWriter sw = new StreamWriter(filePath);
            JsonWriter jsonWriter = new JsonTextWriter(sw);

            jsonWriter.Formatting = Formatting.Indented;
            jsonSerializer.Serialize(jsonWriter, data);

            jsonWriter.Close();
            sw.Close();
        }
    }

And I call it like so:我这样称呼它:

                    Animal animal = new Animal
                    {
                        AnimalName = AnimalNameTextBox,
                        AnimalBreed = AnimalBreedTextBox,
                    };

                    AnimalList Animal = new AnimalList ();
                    JSONParser jsonParser = new JSONParser();

                    if (File.Exists(_animalFilePath))
                    {
                        Animal = jsonParser.JsonDeserialize(typeof(AnimalList), _animalFilePath) as AnimalList;
                    }

                    Animal.ListOfAnimals.Add(animal);

                    jsonParser.JsonSerialize(Animal, _animalFilePath);

Here is Animal Class:这是动物类:

    public class Animal
    {
        public string AnimalName { get; set; }
        public string AnimalBreed { get; set; }

        public Animal()
        {
        }

        public Animal(string AnimalName, string AnimalBreed)
        {
            this.AnimalName = AnimalName;
            this.AnimalBreed = AnimalBreed;
        }
    }

Here is AnimalList Class:这是 AnimalList 类:

    public class AnimalList 
    {
        public List<Animal> ListOfAnimals { get; set; }
        public Animal NewAnimal { get; set; }
        public string AnimalName { get; set; }
        public string AnimalBreed { get; set; }

        public AnimalList()
        {
            ListOfAnimals = new List<Animal>();
        }
    }

It works great so far.到目前为止效果很好。

The JSON object I get while I deserialize it using我使用反序列化它时得到的 JSON 对象

JObject obj = jsonSerializer.Deserialize(jsonReader) as JObject;

is

{{
  "ListOfAnimals": [
    {
      "AnimalName": "Doggie",
      "AnimalBreed": "Dog"
    }
  ],
  "NewAnimal": null,
  "AnimalName": null,
  "AnimalBreed": null
}}

But, I feel I shouldn't need to create an AnimalList class in order to do this, but if I don't do so, when I try to deserialize, JSON doesn't know how to interpret the information inside the JSON file.但是,我觉得我不需要创建 AnimalList 类来执行此操作,但是如果我不这样做,当我尝试反序列化时,JSON 不知道如何解释 JSON 文件中的信息。 I cannot figure it out how to, dynamically, tell JSON that it is a List of Animals.我无法弄清楚如何动态地告诉 JSON 它是一个动物列表。

This is the content of the serialized file created with this method这是用这个方法创建的序列化文件的内容

{
  "ListOfAnimals": [
    {
      "AnimalName": "Doggie",
      "AnimalBreed": "Dog"
    },
    {
      "AnimalName": "Gatito",
      "AnimalBreed": "Cat"
    }
  ],
  "NewAnimal": null,
  "AnimalName": null,
  "AnimalBreed": null
}

I tried without the class AnimalList (just a List<> of Animal), and it creates this file我试过没有类 AnimalList(只是一个 List<> 的 Animal),它创建了这个文件

[
  {
    "AnimalName": "Doggie",
    "AnimalBreed": "Dog"
  }
]

So, it will serialize it but it doesn't know how to deserialize it (this JObject will return null).所以,它会序列化它,但它不知道如何反序列化它(这个 JObject 将返回 null)。

JObject obj = jsonSerializer.Deserialize(jsonReader) as JObject;

What am I doing wrong?我究竟做错了什么? Sorry if it is too lengthy;对不起,如果它太长了; I tried to be as clear as possible.我尽量说清楚。

Thanks谢谢

Thanks to @Sinatr for his help.感谢@Sinatr 的帮助。 This is how I managed to do it without using classes acting as List<>.这就是我在不使用充当 List<> 的类的情况下设法做到的。

        public object JsonDeserialize<T>(string filePath)
        {
            String JSONtxt = File.ReadAllText(filePath);
            var obj = JsonConvert.DeserializeObject<T>(JSONtxt);

            return obj;
        }
        public object JsonDeserialize<T>(string filePath)
        {
            String JSONtxt = File.ReadAllText(filePath);
            var obj = JsonConvert.DeserializeObject<T>(JSONtxt);

            return obj;
        }

Then, call it like so:然后,像这样调用它:

To save to File保存到文件

                    Client client = new Client
                    {
                        ClientName = NameTextBox,
                        ClientAge = Convert.ToInt32(AgeTextBox),
                        ClientStreet = StreetTextBox,
                    };

                    List<Client> ClientList = new List<Client>();
                    JSONParser jsonParser = new JSONParser();    

                    //Check if File exists. If it does, deserialize the file and add the content to the List Client
                    if (File.Exists(_filePath))
                    {
                        ClientList = jsonParser.JsonDeserialize<List<Client>>(_filePath) as List<Client>;
                    }

                    ClientList.Add(client);
                
                    jsonParser.JsonSerialize<List<Client>>(ClientList, _filePath);

To Load from file:从文件加载:

            // First, check if file already exists
            if (!File.Exists(_filePath))
            {
                MessageBox.Show("The file is empty. Please, save some details before trying to load it.");
                return;
            }

            // If file doesn't exist
            else
            {
                JSONParser jsonParser = new JSONParser();
                List<Client> ClientList = jsonParser.JsonDeserialize<List<Client>>(_filePath) as List<Client>;
            }

I hope this can help somebody else.我希望这可以帮助别人。 Thanks again to @Sinatr.再次感谢@Sinatr。

PS: If somebody thinks I am wrong, or there is a better way to do it, please let me know. PS:如果有人认为我错了,或者有更好的方法,请告诉我。 Add your answer or write a comment.添加您的答案或发表评论。 Thank you.谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM