如何使用 JSON 格式创建特定类型的 Javascript 对象

How do I create a Javascript object of a specific type using JSON format?

本文关键字:类型 Javascript 对象 何使用 JSON 格式 创建      更新时间:2023-09-26

我想将地图边界存储在JSON对象中。 对于代码完成,我使用 JSDoc 声明了对象:

/**
 * @name MapBounds
 * @class MapBounds
 * This class represents a map boundary definition.
 *
 * @property {number} minLat Specifies the minimum latitude of the boundary.
 * @property {number} minLon Specifies the minimum longitude of the boundary.
 * @property {number} maxLat Specifies the maximum latitude of the boundary.
 * @property {number} maxLon Specifies the maximum longitude of the boundary.
 */

当需要创建 MapBounds 对象时,我的代码看起来与此类似(此示例没有真正的纬度/纬度值):

var newMapBounds = MapBounds( {minLat: 50, minLon: 50, maxLat: 100, maxLon: 100} );

我使用 JSON 指定对象,然后将其转换为我需要的类型。 有没有更好的方法可以做到这一点?

谢谢。

以下是使用该格式构造 Json 对象的方法(它只是一个 JavaScript 对象文字)

{
 minLat: 0, // Specifies the minimum latitude of the boundary
 minLon: 0, // Specifies the minimum longitude of the boundary
 maxLat: 0, // Specifies the maximum latitude of the boundary
 maxLon: 0  // Specifies the maximum longitude of the boundary
}

将 Json 对象提交到 Web 服务时,必须将 Json 对象"映射"到类是非常典型的。 如果您将 JSON 对象传递给请求并提供对象类型作为 Web 服务参数,某些框架(即 MVC .NET)将为您执行此操作。 尽管如此,上面的格式就是你在 JavaScript 方面表示这种结构的方式。

编辑:从JSON对象到服务器端代码上的指定类的这种类型的映射要么由您在服务器上使用的框架(即.NET/MVC)发生,要么在服务器上手动执行。 将 JSON 对象提交到服务器后,服务器端代码将接管,您不需要在客户端(即 JavaScript)上记录该侧内容。

首先,JavaScript 中没有类。对象是通过调用函数来初始化对象的,继承基于原型链。见 https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain

JSON 只能

存储没有原型链的普通对象,即所有用 JSON 编码的对象都只能继承自Object

因此,可以得出结论,从JSON创建某些类型对象的唯一方法是使用自编写的函数来处理反序列化JSON产生的普通对象。然后,自编写的函数将使用new …调用构造函数来重建原型链。这似乎是你已经在做的事情,这就是你要走的路。

您可以使用一些执行上述步骤的框架来避免手动处理序列化。