2012-07-12 87 views
7

早上,如何从webservice返回JSON

我需要从我的web服务返回一条消息。下面是我的代码示例,并且我返回一个字符串。

[web method] 
public string CheckFeedSubmission() 
    { 
     string responseText = ""; 
     try 
     { 
      //Stuff goes here 
      responseText = "It Worked!" 
     } 
     catch (Exception ex) { responseText = "Opps wehave an error! Exception message:" + ex.Message; } 
     return responseText ; 
    } 

我目前得到如下回应......

<string xmlns="http://tempuri.org/"/> 

我会非常想回到像

{"success" : true, "message" : "***Message Here***"} 

我相信的东西,一旦我得到它的想法,我将能够返回其他物品,如果需要的话。它只是我需要解决的基础。

所有帮助非常感谢,提前:)

UPDATE感谢:刚刚发现这个...

return "{Message:'hello world'}" 

我会需要这样的东西

responseText = "{"success" : true, "message" : \"There has been an error. Message: " + ex.Message + "\"}" 
+0

可能重复[Web服务应返回JSON(http://stackoverflow.com/questions/8205081/web -service-should-return-json) – 2014-02-19 23:47:54

回答

10

用途:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format. 
public string CheckFeedSubmission() 
    { 
     string responseText = ""; 
     try 
     { 
      //Stuff goes here 
      responseText = "It Worked!" 
     } 
     catch (Exception ex) { responseText = "Opps wehave an error! Exception message:" + ex.Message; } 
     return responseText ; 
    } 

返回会像其结果是:

<string xmlns="http://tempuri.org/"/> 
{"success" : true, "message" : "***Message Here***"} 
</string> 
+2

谢谢,但如上所述,我仍然返回XML字符串 – thatuxguy 2012-07-12 08:16:49

+0

实际上,它返回XML内的Json。你需要在你的电话中指定你想要返回的内容。为什么它以格式返回? http://haacked.com/archive/2009/06/25/json-hijacking.aspx – 2012-07-12 08:23:57

+0

“它的工作原理!”回应讯息? – thatuxguy 2012-07-12 08:26:19

2

请使用属性为您的WebMethod

[WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

呼叫者将已经设置了的contentType为application/JSON使用的webmethod

+3

不起作用,仍然只返回一个字符串 - 它工作正常 thatuxguy 2012-07-12 08:16:10

0

试试这个:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format. 
public bool addUser(UserModel um) 
    { 
     bool result = false; 
     result = Conversion.intToBool(SplashAwardsDB.executeNonQuery(
      "INSERT INTO dbo.User (" 
      + "userName, password, firstName, lastName, address, contactNo, birthDate, familyID, familyRole, x, y) " 
      + " VALUES (" 
      + "'" + um.userName + "', " 
      + "'" + um.password + "', " 
      + "'" + um.firstName + "', " 
      + "'" + um.lastName + "', " 
      + "'" + um.address + "', " 
      + "'" + um.contactNo + "', " 
      + "'" + um.birthDate + "', " 
      + "'" + um.familyID + "', " 
      + "'" + um.familyRole + "', " 
      + "'" + um.x + "', " 
      + "'" + um.y + "')" 
      )); 
     return result; 
    }