[英]Javascript JSON custom deserialisation
I'm using a C# app where data classes I use look like this : 我正在使用C#应用程序,其中使用的数据类如下所示:
class Node {
public string name;
public int id;
public Node parent;
public Node[] children;
public Data data;
}
class Community {
public Node[] nodes;
}
class Data {
public string info;
public int value;
}
I declare in javascript these objects : 我在javascript中声明了这些对象:
var Node = {
name: '',
id: '',,
parent: '',
children: '',
data: ''
}
var Community = {
nodes: ''
}
var Data = {
info: '',
value: ''
}
Those are obviously simplified versions of the real deal, but I'd like to know how I can tell the javascript JSON deserializer to build the fields properly, using the objects I declared. 这些显然是实际交易的简化版本,但是我想知道如何告诉javascript JSON反序列化器使用我声明的对象正确构建字段。
I need to make some sort of CMS for this so it's important that all the keys are available, even if they hold no value, which is why I want to declare objects and have the deserialiser use them. 为此,我需要进行某种类型的CMS,因此即使所有键都没有值,所有键都可用非常重要,这就是为什么我要声明对象并让反序列化器使用它们。
For instance, I want to be able to access Community.nodes[3].data.info
even if it wasn't set in the JSON file. 例如,即使没有在JSON文件中设置,我也希望能够访问
Community.nodes[3].data.info
。
A lot of people (including Microsoft ASP.NET) use the NuGet package Json.NET. 很多人(包括Microsoft ASP.NET)都使用NuGet包Json.NET。
The JsonSerializer
class offers a large degree of customisation over how objects are serialized. JsonSerializer
类提供了有关如何序列化对象的大量定制。
However to access a deeply nested field like Community.people[3].job.salary
you must make sure that there are no null nested objects before you access the last field. 但是,要访问诸如
Community.people[3].job.salary
类的深层嵌套字段,您必须在访问最后一个字段之前确保没有空嵌套对象。
In your example you would probably want to set Person.Job
to be a default value or pass the Job
in the constructor for Person. 在您的示例中,您可能希望将
Person.Job
设置为默认值,或在Person的构造函数中传递Job
。
If the issue is on the JavaScript side I suggest you take a look at the prototype pattern as a starting point and this question for reference to assigning to it from a JSON string. 如果问题出在JavaScript方面,建议您以原型模式为起点,并参考此问题以从JSON字符串分配给它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.