如何使用json.net构建对象层次结构以进行序列化? [英] How to build object hierarchy for serialization with json.net?
问题描述
我正在尝试正确编写代码以构建要序列化为json的数据结构.
I'm trying to properly write code to build a data structure to serialize into json.
我正在使用json.net.
I'm using json.net.
我不想创建一堆类来保存这些数据,因为我认为json.net中应该已经有一些类可以做到这一点
I don't want to create a bunch of classes to hold this data, as I thought there should be some classes that will already do this in json.net
我已经在一系列嵌套循环中获得了所需的所有数据,现在我只想在将它们运行到JsonConvert.SerializeObject之前将它们添加到对象层次结构中.
I've already got all the data I need in a series of nested loops, and now I just want to add them to an object hierarchy before I run JsonConvert.SerializeObject on it.
我已经尝试过这样的代码,但是它似乎不起作用
I've already tried code like this, but it doesn't seem to work
JArray container = new JArray();
container.Add(new JObject(new JProperty("name", "Client1"), new JProperty("projects", new JArray())));
container[0].AddAfterSelf(new JObject(new JProperty("projects", new JArray())));
container[1].AddAfterSelf(new JObject(new JProperty("projects", "Project2")));
container[1].AddAfterSelf(new JObject(new JProperty("projects", "Project3")));
container.Add(new JProperty("name", "Client2"));
var test = JsonConvert.SerializeObject(container);
问题是,当我使用[i]时.或ElementAt(i)来访问结构中的某个位置,.Add()丢失或.ElementAt不存在. 我该如何逐步遍历数据结构以使其在下面很好地输出,还是必须为所有这些创建自己的容器类?
The problem is that when I use [i]. or ElementAt(i) to access somewhere in the structure, either .Add() is missing or .ElementAt isn't there. How do I step through the data structure to make this nicely output the below, or do I have to create my own container class for all of this?
这是我要制作的数据格式.
This is the data format I am trying to make.
[
{
"name": "student1",
"projects":
[
{
"name": "Project1",
"tasks":
[
{
"name": "task1",
"id": 2
}
],
"id": 6
}
]
},
{
"name": "Student2",
"projects": [
{
"name": "Project1",
"tasks": [
{
"name": "Task2",
"id": 1
},
{
"name": "Task3",
"id": 3
},
{
"name": "Task4",
"id": 4
}
],
"id": 2
等...
推荐答案
我认为您要问的是如何在json中序列化复杂的业务对象,但仅公开某些属性.
I think what you're asking is how to serialize complex business objects in json, but only expose certain properties.
换句话说,您已经有一个学生列表,但是您只想通过json发送非常具体的数据.如果我错了,这个答案将不适合您的需求.
In other words you already have a list of students, but you only want to send very specific data via json. If I'm wrong this answer won't suit your needs.
因此,假设您有一个学生列表,并且项目属性具有任务的内部属性,那么这就是我使用匿名对象而无需创建大量新类的方法.
So assuming you have a list of students, with a projects property that has an inner property of tasks, this is how I do it without having to create loads of new classes, I use anonymous objects.
创建匿名对象列表后,只需将它们转换为json字符串即可.
Once I've created my list of anonymous objects, I simply turn them into a json string.
正如注释中指出的那样,您无需使用json.net,此功能在框架中可用,在System.Web.Extensions.dll
之后添加引用,然后
As pointed out in the comments you don't need to use json.net, this functionality is available in the framework, add a reference to System.Web.Extensions.dll
then
使用System.Web.Script.Serialization;
using System.Web.Script.Serialization;
var jsonStudents = new List<object>();
foreach (var student in students)
{
jsonStudents.Add(new
{
student.Id, //anonymous properties automatically pick up the name of the property you pass them, this will be called Id
FullName = student.FirstName + " " + student.LastName, //if you want to name a property yourself use this notation
Projects = student.Projects.Select(p => new //this will be an enumerable of nested anonymous objects, we're partially selecting project properties
{
p.Id,
p.Name,
Tasks = p.Tasks.Select(t => new //nesting another level
{
t.Id,
t.Name
})
})
});
}
var serializer = new JavaScriptSerializer();
var jsonString = serializer.Serialize(jsonStudents);
如果您真的想使用循环,则可以执行以下操作以允许您在创建项目和任务时做更复杂的事情:
If you really want to use loops you can do this to allow you to do more complicated things in the creating of the projects and tasks:
var jsonStudents = new List<object>();
foreach (var student in students)
{
var tempStudent = new
{
student.Id, //anonymous properties automatically pick up the name of the property you pass them, this will be called Id
FullName = student.FirstName + " " + student.LastName, //if you want to name a property yourself use this notation
Projects = new List<object>()
};
foreach (var project in student.Projects)
{
var tempProject = new {
project.Id,
project.Name,
Tasks = new List<object>()
};
foreach (var task in project.Tasks)
{
tempProject.Tasks.Add(new {
task.Id,
task.Name
});
}
tempStudent.Projects.Add(tempProject);
}
jsonStudents.Add(tempStudent);
}
var serializer = new JavaScriptSerializer();
var jsonString = serializer.Serialize(jsonStudents);
这篇关于如何使用json.net构建对象层次结构以进行序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!