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

标签 javascript json

我想将 map 边界存储在 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 对象传递给请求并提供对象类型作为 Web 服务参数,某些框架(即 MVC .NET)将为您执行此操作。尽管如此,上面的格式是您在 JavaScript 方面表示该结构的方式。

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

关于javascript - 如何使用 JSON 格式创建特定类型的 Javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14529620/

相关文章:

javascript - "Cannot set color of undefined"是什么意思?

javascript - 使用 toastr 获取 'Cannot read property ' 然后“未定义”

javascript - 使用 React 高阶组件获取所有子组件 href

javascript - 无法将 JSON 结果传递回 View

java - JSON 泛型集合反序列化

javascript - 如何在 Angular JS 中一一显示 json 数组中的项目

json - 我的 JSON 解析不起作用

java - 如何配置 Jackson ObjectMapper 以仅显示白名单属性?

javascript - 转换为引导 : Notification undefined

javascript - 使用 webpack 将 Wasm + JS 文件捆绑为一个