如何在Web服务中返回JSON?

时间:2010-05-27 21:25:30

标签: asp.net web-services asp.net-3.5

我需要一个Hello World示例......

[WebService(Namespace = "xxxxx")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService()]
public class Something : System.Web.Services.WebService
{
    public Something() { }

    [WebMethod]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    public string HelloWorld()
    {
        return "{Message:'hello world'}";
    }
}

因为它会产生错误

{"Message":"Invalid JSON primitive: value.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

怎么了?

编辑:如果我需要返回{Message:'',Type:1}怎么办?

编辑2:最后一个的答案是:我可以返回Dictionary<string, string>

2 个答案:

答案 0 :(得分:5)

您只需要从函数中返回正常(即非JSON)字符串,如:

 return "Hello World"

假设您使用的是.Net 3.5,您的JSON响应将是:

 {"d":"Hello World"}

答案 1 :(得分:1)

好吧,如果你需要你的JSON在{Message:Hello wolrd}对中的exactelly (或者如果您计划将Web服务用于更复杂的事情),您可能需要为此创建一个可序列化的类

[Serializable]
class MessageClass
{
    public string Message {get;set;}

    //any public member will automatically  be serialized  as JSON
    punlic bool WillAlsoBeJsoned {get;set;}

    //unless explicitly told not to
    [NonSerialized] 
    [ScriptIgnoreAttribute]
    public string WillNotBeJsoned {get;set;}
}

然后在您的网络服务中

     //{Message :"Hello World",WillAlsoBeJsoned :false}
    [WebMethod] 
    public string HelloWorld() 


       { 
             var returnObject = new MessageClass();
             returnObject.Message= "Hello World";
             var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();        
            return  oSerializer.Serialize(returnObject);
} 

    // return an array of the same items
    //[{Message :"Hello World",WillAlsoBeJsoned :false},
    //{Message :"something else",WillAlsoBeJsoned :false}]
    [WebMethod] 

        public string HelloWorldList() 
        { 
             var returnObject = new List<MessageClass>();

             var message1= new MessageClass();       
             message1.Message= "Hello World";

             var message2= new MessageClass();
             message2.Message= "something else";

             returnObject.Add(message1);
             returnObject.Add(message2);

             var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();        
            return  oSerializer.Serialize(returnObject);

}