从单独的类序列化和反序列化JSON对象,而无需拥有独立的类? [英] Serialize and deserialize JSON object from separate classes without need to have stand-alone class?
问题描述
是否有可能从两个类形成一个对象,然后将其序列化为JSON,反序列化时,就可以获取这两个对象.
说我有:Student
和List<Course>
的对象
是否可以将这两个对象合并为一个JSON对象.
我需要这样做是因为在我正在处理的项目中为每个JSON对象建立一个类会非常耗费精力!
Is it possible to form an object from two classes and then serialize it to JSON, and when deserialize it back be able to get those two objects.
say I have: an object of Student
and a List<Course>
is it possible to combine these two objects in one JSON object.
I need this because building up a class for every JSON object would be very exhausting in the project I'm working on!
推荐答案
Is it possible to form an object from two classes and then serialize it to JSON
例如,这里是一个示例
class Student
{
public string Name { get; set; }
}
class Course
{
public string Title { get; set; }
}
var std = new Student() {Name = "foo"};
var lstCours = new List<Course>() { new Course(){Title = "math"}};
var stdJson = JsonConvert.SerializeObject(new {student=std});
var lstCoursJson = JsonConvert.SerializeObject( new{Cours= lstCours});
JObject jObjectStd = JObject.Parse(stdJson);
JObject jObjectLstCours = JObject.Parse(lstCoursJson);
jObjectStd.Merge(jObjectLstCours,new JsonMergeSettings(){MergeArrayHandling = MergeArrayHandling.Concat});
Console.WriteLine(jObjectStd.ToString());
这是您合并后得到的东西
here what you get as a merge
{
"student": {
"Name": "foo"
},
"Cours": [
{
"Title": "math"
}
]
}
使用JSON.net进行反序列化非常简单
to deserialize this is pretty simple with JSON.net
var stdParsed = JObject.Parse(json).Property("student").Value.ToString();
var lstCoursParsed = JObject.Parse(json).Property("Cours").Value.ToString();
var stdDes = JsonConvert.DeserializeObject<Student>(stdParsed);
var lstCoursDes = JsonConvert.DeserializeObject<List<Course>>(lstCoursParsed);
这篇关于从单独的类序列化和反序列化JSON对象,而无需拥有独立的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!