2012-07-12 129 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; 
    }