3

I have a class CodeWithMessage that I want to return from my webservice as json.

The class is defined as such

namespace UserSite //Classes For my site
{
 namespace General
 {
 public class CodeWithMessage
 {
 private int iCode = 0;
 private string sMessage = "";
 public CodeWithMessage(int Code, string Message)
 {
 iCode = Code;
 sMessage = Message;
 }
 public CodeWithMessage()
 {
 }
 public void Message(string lMessage)
 {
 sMessage = lMessage;
 }
 public void Code(int lCode)
 {
 iCode = lCode;
 }
 }

In the Webservice I have

[WebMethod(Description = "Creates A New Blog.")]
 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
 public CodeWithMessage AddNewBlog(string sTitle, string sDescription, string sOohrl, int iCategory=30)
 {
 CodeWithMessage CWM;
 CWM = new CodeWithMessage();
 CWM.Message("That url Is In Use");
 CWM.Code(0);
 return CWM;

I am posting the correct values (I truncated the function but it's getting what it needs and executing) I get back

{"d":{"__type":"UserSite.General.CodeWithMessage"}}

I'm not sure why I am not getting back an actual json object with the values but rather just the class name?? I thought asp.net would automatically serialize the object? Does it not??

Thanks in advance

rick schott
21.1k5 gold badges54 silver badges81 bronze badges
asked Nov 28, 2011 at 2:03

1 Answer 1

3

You have to use public properties for the JavaScriptSerializer to serialize the JSON like you want. The JavaScriptSerializer cannot expose the methods nor the private fields.

namespace UserSite //Classes For my site
{
 namespace General
 {
 public class CodeWithMessage
 { 
 public int Code { get; set; }
 public string Message { get; set; }
 }
 }
}
..............
//usage
CodeWithMessage CWM = new CodeWithMessage();
CWM.Message = "That url Is In Use";
CWM.Code = 0;
return CWM;
answered Nov 28, 2011 at 2:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.