代码之家  ›  专栏  ›  技术社区  ›  Mironline Naeem Bashir

ASP.NET Web服务和JSON结果中的额外量化!

  •  0
  • Mironline Naeem Bashir  · 技术社区  · 14 年前

    我想用javascript调用一个Web服务方法。(ASP.NET 3.5)

    我用萤火虫追踪结果。 结果如下:

    {"d":"[{\"TI\":\"www\"},{\"TI\":\"www1\"}]"}
    

    我想正确的结果应该是这样的

    {"d":[{\"TI\":\"www\"},{\"TI\":\"www1\"}]}
    

    什么是 引用 支架前后?

    /编辑: 在WebServCE中:

    public class Test
        {
            public Test(string t){T1 = t;}
            public string T1 { set; get; }
        }
    
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
        public string Load(string e)
        {
            List<Test> post = new List<Test> { new Test("www"), new Test("www1") };
            return JsonConvert.SerializeObject(post);
        }
    

    在JS文件中:

     var store = new Ext.data.JsonStore({
            proxy: new Ext.data.HttpProxy({
                url: '/core/webservice/service.asmx/Load',
                method: 'GET',
                headers: { 'Content-type': 'application/json' }
            }),
            root: 'd',
            id: 'Id',
            fields: ['TI']
        });
        store.load({ params: { e: ''} });
        return; 
    

    谢谢您。

    密尔

    2 回复  |  直到 14 年前
        1
  •  1
  •   peol    14 年前

    您不需要在Web服务中手动序列化;请考虑使用类似这样的方法:

    public List<Test> Load(string e)
    {
        List<Test> post = new List<Test> { new Test("www"), new Test("www1") };
        return post;
    }
    

    因为你在使用 string 作为您的返回对象,它将在序列化时(再次)将其转换为您的返回对象。

        2
  •  1
  •   sTodorov    14 年前

    引号表示这是一个字符串,因此:

    var b = {"d":"[{\"TI\":\"www\"},{\"TI\":\"www1\"}]"};
    

    b[“d”]将返回一个字符串而不是对象数组。 在javascript中,您可以使用以下方法来解决这个问题:

    var c = eval(b["d"]);
    

    它将把字符串转换成对象数组。 或者更好的方法,发布返回这个值的代码,我们可以尝试找出为什么它作为字符串返回。