公开一个特定的.NET对象为JSON [英] Expose a specific .net object as JSON

查看:139
本文介绍了公开一个特定的.NET对象为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在使JSON调用使用ScriptService属性,我的Web服务。问题是,我的一个类引用第二类和.Net不捡,写了JavaScript的第二类。

I'm currently enabling JSON calls to my web services using the ScriptService attribute. The problem is that one of my classes references a second class and .Net is not picking up and writing out the JavaScript for the second class.

作为一种变通方法,我可以写,只是返回第二类的虚拟方法。然后净写入JSON允许它被序列化。因此,在下面的示例:

As a workaround I can write a dummy method that just returns the second class. Then .Net writes the JSON to allow it to be serialized. So in the following example:

[ScriptService]
public class MyService : WebService {
    [WebMethod]
    public void SaveClass1(Class1 class1) {
        ...
    }
}

[Serializable]
public class Class1 {
    public Class2 class2 { get; set; }
}

[Serializable]
public class Class2 {
}

MyService.asmx / JS不会写code,让我实例化的Class2为了让我来填充1级。不过,我可以让它工作,如果我补充一下:

MyService.asmx/js won't write code to allow me to instantiate Class2 in order for me to populate Class1. But I can make it work if I add:

[WebMethod]
public Class2 Dummy() {
    return new Class2();
}

为了MyService。我讨厌的解决办法的任何替代品将大大AP preciated。

to MyService. Any alternatives to my nasty workaround would be greatly appreciated.

推荐答案

您需要使用<一个href="http://msdn.microsoft.com/en-us/library/system.web.script.services.generatescripttypeattribute.aspx"相对=nofollow> System.Web.Script.Services.GenerateScriptTypeAttribute ,它指定一个服务器类型应包含在生成的代理code。您可以将此属性的Web服务本身或任何方法标记的 WebMethodAttribute

You need to use System.Web.Script.Services.GenerateScriptTypeAttribute, which specifies that a server type should be included in the generated proxy code. You can apply this attribute to the web service itself or any method marked with WebMethodAttribute.

例如:

[ScriptService]
[GenerateScriptType(typeof(Class2))]
public class MyService : WebService {
    [WebMethod]
    public void SaveClass1(Class1 class1) {
        // ...
    }
}

这篇关于公开一个特定的.NET对象为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆