javascript - NewtonSoft JSON 转换器序列化但执行起来很奇怪。怎么修?

标签 javascript jquery json vb.net json.net

给定以下对象

Friend Class GetLocationsResult
    Public Property X1 As String
    Public Property X2 As String
    Public Property X3 As String
    Public Property X4 As String
    Public Property X5 As String
    Public Property X6 As Double
    Public Property X7 As Double
End Class

它是这样声明和实例化的:

Dim objList as List(of GetLocationsResults) = new List(of GetLocationsResults)

并且 objList 是通过一个迭代器填充的,该迭代器遍历对象/聚合类的集合。迭代器只是将值插入新的 GetLocationsResult 对象,然后将其添加到列表中。

并给出 NewtonSoft JSONConvert.SerializeObject(objList) 结果:

{"d":"[{\"X1\":\"店铺名称\",\"X2\":\"地址\",\"X3\":\"城市\",\"X4\":\"State\",\"X5\":\"Zip\",\"X6\":坐标1,\"X7\":坐标2}]"}

This point has been addressed and is no longer an issue

There are several issues with this result set. First, for whatever odd reason, the object being named "d" is not acceptable.

  1. How can I specify something other than "d" for the "name" of the json array?

当我尝试 JSON.parse 响应时,它需要采用以下格式才能真正获取数据:

resultSet = JSON.parse(data.d);
console.warn(resultSet[0].X1);

不得不说 resultSet[0] 当然是 Not Acceptable 。

  1. How do I cause the 'JSONConvert.Serialize' method to not wrap the response in such a way that I have to refer to the first index of the resulting JSON data so that I can say resultSet.X1 instead of resultSet[0].X1?

根据要求,这里有一些可能与当前问题相关的更详细的信息。

正在从 WCF 服务返回数据。暴露的方法是这样装饰的:

<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json)>

并返回类型String。该服务由桌面应用程序和移动平台使用。桌面网站可以有自己的方法,事实上,这样做是因为我们不想处理 X1、X2 等,而移动平台开发人员已声明这是必要的。如前所述,该方法以自定义聚合类的形式返回许多结果,然后将这些结果推送到一个仅是属性集合的类对象中。因此返回语句是:

Return JsonConvert.SerializeObject(retVal)

其中 retVal 是一个列表(包含 GetLocationsResult)

因此,虽然必须通过索引访问数据对于网站来说可能没问题,但对于移动平台来说是 Not Acceptable 。因为每个人都将运行自己的方法,所以如果需要,可以为两者提供独特的解决方案。

最佳答案

三件事。

  1. 听起来您是通过 ASP.NET ASMX 返回的 ScriptService 或 ASPX [WebMethod]。当使用其中之一时 端点,you don't need to (and shouldn't) manually serialize the object into JSON . ASP.NET 会自动为您完成。您根本不需要使用 JSONConvert;只需返回您的对象作为结果。这就是您在 .d 之后看到所有转义数据的原因。它是 JSON 序列化两次。

  2. 正如 WhiteHat 所提到的,.d 在某些情况下是一件好事。它在这些 ASP.NET JSON 服务中默认引入,无法在服务器端轻易删除,但在客户端解析响应时很容易考虑。

  3. 您正在返回一个 List(of GetLocationResults),它映射到一个 JavaScript 数组。这就是为什么您需要使用 resultSet[0].X1 来访问结果中的值。如果您想通过 resultSet.X1 访问该值,您需要确保只返回一个 GetLocationResults 对象,而不是它们的列表。

这有帮助吗?如果您可以使用更完整的服务器端和客户端代码示例来更新您的问题,我可以举例说明如何解决上述三个问题。

关于javascript - NewtonSoft JSON 转换器序列化但执行起来很奇怪。怎么修?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32486778/

相关文章:

JavaScript 改变对象内部的变量

javascript - 在 ie11 上使用 jquery 滚动会出现抖动元素问题

json - 如何使用 rabbitmqadmin 命令发布 Json

javascript - 将 json 数据发布到 Node api 时出现超时问题

javascript - 将闪烁边框应用于 appcelerator 中的表格 View

javascript - 如果尚未可用,则在 jQuery 加载时执行

javascript - JS 递归函数破解

javascript - jQuery - 将表单提交到 RESTful URL

javascript - 我有以下代码来刷新 div,而不是整个 html 页面

java - 尝试从 Json Web 响应获取 Json 节点时出错