您在标题中提到了 GSON,但我不确定它在这张图片中的作用。所以,我可能偏离了错误的切线。但是,如果您只是询问如何让 .NET 反序列化您的 JSON,是的,您可以使用 __type 参数。它必须是第一位的。
{"obj":{"__type":"B","name":"waqas","address":"sweden"}}
我能够让它在测试项目中工作,但就像我说的,不涉及 GSON。
EDIT:其实你可能还想看看这个其他答案https://stackoverflow.com/a/10805715/1539015 https://stackoverflow.com/a/10805715/1539015讨论如何让 GSON 包含 __type 参数。
EDIT2:我创建了一个新的 .NET 网站。添加了包含 A 类和 B 类的类文件(修改为公开):
public class A
{
public string name;
}
public class B : A
{
public string address;
}
然后我添加了一个 Web 服务来获取问题中的 WebMethod。我还包含了一个 GetJson 方法。这是背后的代码:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[WebMethod]
public B GetJson()
{
return new B() { address = "addr", name = "nm" };
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string PushJson(A obj)
{
B b = (B)obj;
return b.address;
}
}
然后我编辑了默认页面以使用 jQuery 调用 Web 方法:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
<div id="GetResult">Click here for the result of getting json.</div>
<div id="PushResult">Click here for the result of pushing json.</div>
</p>
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#GetResult").click(function () {
$.ajax({
type: "GET",
url: "WebService.asmx/GetJson",
contentType: "application/json; charset=utf-8",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#GetResult").text(msg.d.name);
}
});
});
$("#PushResult").click(function () {
$.ajax({
type: "POST",
url: "WebService.asmx/PushJson",
data: '{"obj":{"__type":"B","name":"waqas","address":"sweden"}}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#PushResult").text(msg.d);
}
});
});
});
</script>
</asp:Content>
如果在 PushJson 的 webservice 方法中放置一个断点,您可以看到创建的对象是 B 类型,并且它运行时还显示它可以转换为 B 类型并使用。
这里没有 GSON,但我相信我链接的另一篇文章应该展示如何让 GSON 生成 __type 参数。