How to return JSON from webservice

Morning,

I need to return a message from my web service. Below is a sample of my code, and i am returning a string.

[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 ;
    }

I currently get the following response…
<string xmlns="http://tempuri.org/"/>

I would ideally like to return something like
 {"success" : true, "message" : "***Message Here***"}

I am sure once i get the idea of it, i will be able to return other items if needed. Its just this base i need to work out.

All help is much appreciated, thanks in advance 🙂

UPDATE: Just found this…

 return "{Message:'hello world'}"

Would i need something like
 responseText = "{"success" : true, "message" : "There has been an error. Message: " + ex.Message + ""}"

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use:

[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 ;
    }

The result returned will be like:
<string xmlns="http://tempuri.org/"/>
 {"success" : true, "message" : "***Message Here***"}
</string>

Method 2

Please use the attribute for your webmethod

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

The caller will have set his contenttype to application/json to use the webmethod

Method 3

Try this one :

[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;
    }

Method 4

To remove the XML tags in your service response, see this answer on StackOverflow:

ASP.NET WebService is Wrapping my JSON response with XML tags

Method 5

This my solution for the framewok 4.5.2,
In the class FilterConfig add the following code,
Note: you will need the lib Newtonsoft.

 public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
        GlobalConfiguration.Configuration.EnableCors();
        filters.Add(new HandleErrorAttribute());
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x