我看到了类似的问题,但它没有解决我的问题.我在ASMX文件中有一个JSON Web服务;
Web方法的代码
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetUserRoles(string JSONUserCode)
{
string retRoles = string.Empty;
List<JSONRole> roles = new List<JSONRole>();
{... I Populate the roles here ...}
DataContractJsonSerializer serializer = new
DataContractJsonSerializer(roles.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, roles);
string jsonString = Encoding.Default.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
Run Code Online (Sandbox Code Playgroud)
这正确地正确地格式化List,但是用XML包装整个返回.以下是回复:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://formshare.com/">
[{"Name":"Accounts Payable"},{"Name":"Payroll"}]
</string>
Run Code Online (Sandbox Code Playgroud)
您可以通过单击此链接查看自己的响应:
http://dev.formshare.gologictech.com/JSON/JSONService.asmx/GetUserRoles?JSONUserCode=1234
我需要的回应是:
[{"Name":"Accounts Payable"},{"Name":"Payroll"}]
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢你的帮助.
我不确定我错过了什么,我错过了什么.
我正在构建一个ASP.NET 2.0(在.Net 3.5框架上)Web应用程序,我正在包含一个Web服务.请注意,这不是 MVC项目.我希望公开一个返回JSON字符串的方法; 格式化以提供jqGrid jQuery插件.
这是我在我的服务中实现的初步测试方法:感谢(Phil Haack的MVC指南)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getData()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonData = new
{
total = 1, // we'll implement later
page = 1,
records = 3, // implement later
rows = new[]{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?", "yay"}},
new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?", "yay"}},
new …Run Code Online (Sandbox Code Playgroud) 我需要我的Web服务才能返回JSON ...
我的.asmx文件中有以下代码:
namespace Feed
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class searchPerson : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Person GetDave()
{
Person dave = new Person();
dave.FirstName = "Dave";
dave.LastName = "Ward";
return dave;
}
}
}
Run Code Online (Sandbox Code Playgroud)
返回以下内容:
<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<FirstName>Dave</FirstName>
<LastName>Ward</LastName>
</Person>
Run Code Online (Sandbox Code Playgroud)
如何强制它返回JSON而不是XML?