【问题标题】:JSON not parsed into custom objectJSON 未解析为自定义对象
【发布时间】:2017-01-09 13:22:50
【问题描述】:

请看下面的 AJAX:

 <script type="text/javascript"  src="Javascript/json2.js"></script>
    <script type="text/javascript" src="Javascript/jquery-1.11.1.min.js"></script>
    <script type = "text/javascript">
        function GetData() {
            $.ajax({
                type: "POST",
                url: "JSONExample.aspx/GetPerson",
            contentType: "application/json; charset=utf-8",
            dataType: "text",
            success: OnSuccess(),
            //async: false,
            failure: function (response) {
                alert('there was an error counting possibles')
            }
        });

        function OnSuccess() {
            return function (response) {
                alert(response);
                window.location.href("JSONExample.aspx?id=" + response);
            }
        }
        }
        GetData()
    </script>

以及下面的服务器端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Newtonsoft.Json;

namespace SerializeAndDeserializeJSON
{
    //[Serializable]
    public class Person
    {
        public String Name;
        public int Age;
    }

    public partial class JSONExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((Request.QueryString["id"]== null)==false)
            {
                var json = Request.QueryString["id"];
                var person = JsonConvert.DeserializeObject<Person>(json); //person is null
            }
        }

        [System.Web.Services.WebMethod]
        public static Person GetPerson()
        {
            Person p1 = new Person();
            p1.Name = "Ian";
            p1.Age=35;
            return p1;
        }
    }
}

页面加载后Person对象的值如下:

名称:空 年龄:0

名字应该是 Ian,年龄应该是 35。我做错了什么?

【问题讨论】:

  • 检查您的响应是否为空,将 dataType 更改为 json
  • OnSuccess函数内部的Json对象无效吗?

标签: c# json web-services


【解决方案1】:

我做错了什么?

尝试将 dataType 设置为 json 而不是 text

dataType: 'json'

然后在id参数中将javascript对象作为JSON字符串发送:

window.location.href("JSONExample.aspx?id=" + encodeURIComponent(JSON.stringify(response.d)));

请注意,我们在这里使用response.d,因为 ASP.NET WebMethods 使用此特殊属性序列化响应。

您可能还想为模型使用公共属性而不是字段:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

一些框架在字段上阻塞。

【讨论】:

  • 谢谢。但是,这会在服务器端产生错误:“无法从 System.String 转换或转换为 SerializeAndDeserializeJSON.Person。”
  • 你在服务器上得到的id参数的值是多少?
  • \"{\\\"d\\\":{\\\"__type\\\":\\\"SerializeAndDeserializeJSON.Person\\\",\\\"名称\ \\":\\\"伊恩\\\",\\\"年龄\\\":35}}\
  • 好的,我明白了。使用dataType: 'json',然后使用JSON.stringify(response.d)。我已经更新了我的答案以反映这一变化。需要注意的是使用response.d
  • 谢谢。做到了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
相关资源
最近更新 更多