C# 在C中使用JSON动态序列化和反序列化#
首先,我认为我正在尝试动态地序列化和反序列化,而不是以编程方式。对不起,如果我在标题上出错了 我是一名软件工程专业的学生,我正在努力学习一些关于JSON的知识。我创建了一个类(我可能会将它用作项目的.dll)来序列化和反序列化C# 在C中使用JSON动态序列化和反序列化#,c#,json,dynamic,json-deserialization,json-serialization,C#,Json,Dynamic,Json Deserialization,Json Serialization,首先,我认为我正在尝试动态地序列化和反序列化,而不是以编程方式。对不起,如果我在标题上出错了 我是一名软件工程专业的学生,我正在努力学习一些关于JSON的知识。我创建了一个类(我可能会将它用作项目的.dll)来序列化和反序列化 public class JSONParser { public object JsonDeserialize(Type dataType, string filePath) { JsonSerial
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();
}
}
我这样称呼它:
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);
这是动物课:
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;
}
}
这是动物主义者的课程:
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>();
}
}
是
但是,我觉得我不需要创建一个AnimalList类来实现这一点,但是如果我不这样做,当我尝试反序列化时,JSON不知道如何解释JSON文件中的信息。我不知道如何动态地告诉JSON这是一个动物列表
这是使用此方法创建的序列化文件的内容
{
"ListOfAnimals": [
{
"AnimalName": "Doggie",
"AnimalBreed": "Dog"
},
{
"AnimalName": "Gatito",
"AnimalBreed": "Cat"
}
],
"NewAnimal": null,
"AnimalName": null,
"AnimalBreed": null
}
我尝试不使用AnimalList类(只是一个动物列表),它创建了这个文件
[
{
"AnimalName": "Doggie",
"AnimalBreed": "Dog"
}
]
因此,它将序列化它,但不知道如何反序列化它(此JObject将返回null)
我做错了什么?
抱歉,如果太长了;我尽量说清楚
感谢@Sinatr的帮助。 这就是我在不使用类作为列表的情况下如何做到的 公共对象JsonDeserialize(字符串文件路径) { 字符串JSONtxt=File.ReadAllText(文件路径); var obj=JsonConvert.DeserializeObject(JSONtxt); 返回obj; } 公共对象JsonDeserialize(字符串文件路径) { 字符串JSONtxt=File.ReadAllText(文件路径); var obj=JsonConvert.DeserializeObject(JSONtxt); 返回obj; } 那么,就这样称呼它:
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);
保存到文件
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);
Client=新客户端
{
ClientName=NameTextBox,
ClientAge=Convert.ToInt32(AgeTextBox),
ClientStreet=StreetTextBox,
};
List ClientList=新列表();
JSONParser JSONParser=新的JSONParser();
//检查文件是否存在。如果是,则反序列化文件并将内容添加到列表客户端
if(File.Exists(_filePath))
{
ClientList=jsonParser.JsonDeserialize(_filePath)作为列表;
}
ClientList.Add(客户端);
jsonParser.JsonSerialize(ClientList,_filePath);
要从文件加载,请执行以下操作:
// 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>;
}
//首先,检查文件是否已经存在
如果(!File.Exists(_filePath))
{
Show(“文件为空。请在尝试加载之前保存一些详细信息。”);
返回;
}
//如果文件不存在
其他的
{
JSONParser JSONParser=新的JSONParser();
List ClientList=jsonParser.JsonDeserialize(_filePath)作为列表;
}
我希望这能帮助别人。
再次感谢@Sinatr
如果有人认为我错了,或者有更好的方法,请告诉我。添加您的答案或写评论。谢谢。它返回
null
,因为您序列化了数据(AnimalList
实例),它将反序列化您试图转换到JObject
的同一类型(不可能,因此null
)。考虑使用泛型<代码>反序列化< /代码>,这将简单地调用JSON.NET的泛型方法。然后你可以简单地调用反序列化()
。不,不,我想我解释错了。如果我使用AnimalList类,一切都很好。问题是当我试图避免使用类AnimalList时,我只是创建了一个列表,以避免创建额外的类AnimalList。我不知道,我认为这只是额外的代码行(以及json文件的外观,它与我在其他地方看到的不一样)。我将重新表述:要使反序列化
方法对任何东西都有效,需要将类型参数传递给它。如果您在编译时知道类型,那么泛型是最方便的方法;对不起,我太笨了<代码>公共对象JsonDeserialize(类型数据类型,字符串文件路径)
调用自:List Animal=jsonParser.JsonDeserialize(typeof(List),_animalFilePath)as 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;
}
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);
// 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>;
}