Developing an ASP.NET application that returns a custom object in JSON format

I have a class called CodeWithMessage that I need to return as a json object from my web service.

Here is how the class is defined:

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

Within the web service, I have the following method:

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

After making the call, I am expecting a json object with the values, but instead, I am receiving this response:

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

I am confused as to why I am not getting the actual json object with values. I thought asp.net would handle serialization automatically. Is that not the case?

Thank you for your help.

Answer №1

To achieve the desired JSON serialization, it is necessary to utilize public properties when working with the JavaScriptSerializer. This is because the JavaScriptSerializer does not have access to methods or 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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to alter the timestamp on comments in a React Native app, similar to Instagram's functionality, using dayjs?

I am currently working on a project using react native in combination with dayjs library. My goal is to compare the timestamp of when a comment was written with the current time, and then display this compared time using console.log() with the help of day ...

"Vue js: Embracing Labeling and Agile Transformation in Dynamic

Is it possible to dynamically change the input field's type and label between text, email, and number in Vue.js? I am new to this framework and would like to learn how to do this. <input type="email"> ...

The Vue.js checkbox linked to a v-model with a value set to false is currently marked as

I'm attempting to create a to-do list resembling the Eisenhower matrix, but I'm encountering an issue with v-bind and v-model being triggered incorrectly. How can I resolve this bug? https://i.sstatic.net/iIhqR.png Code inspiration from Vue.js T ...

Exception encountered while trying to map JSON data

I am encountering an issue while attempting to send JSON data to my JAVA class. "Failed executing POST IntakeFormSections/PostData: org.jboss.resteasy.spi.ReaderException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of org. ...

To make the Bootstrap 4 spinner/loader gracefully disappear when the browser window has finished loading, utilize the fadeOut() or hide() function

THE GOAL My objective is to display a spinner/loader while the browser window is loading, and then have it fade or hide once the page is fully loaded. EFFORTS MADE I've attempted to use a jQuery code recommended in a different question (How to show ...

What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname ...

How can you transform square bracket object keys from a URL address into a nested object using Javascript?

Considering the following: var obj = { "object[foo][bar][ya]": 100 }; Is there a way to achieve this structure: var obj = { object: { foo: { bar: { ya: 100 }}}}; ...

Using three.js to retrieve the camera's position using orbit controls

In my journey using three.js orbit controls, I have encountered a challenge of making a skybox follow the camera's position. Despite scouring the internet, I have not come across a suitable solution. My query is straightforward - how can I obtain the ...

Combining dictionaries while preserving distinct values

I'm attempting to combine a set of dictionaries to achieve a specific outcome. Here is the list of dictionaries I am working with: data = [{'city': 'San Francisco', 'state': 'CA', 'id': 1, 'name& ...

What is the best way to connect these functions in a sequence using promises?

A new software has been developed to extract data from an online t-shirt store and then organize the product information into a CSV file. The software consists of 3 scraping functions and 1 function for writing the data. I'm currently facing challen ...

What could be causing my resize event to not trigger?

My goal is for the #sequence div to be full height of the browser window when the window size is greater than 920px in height. In such cases, I also want to trigger a plugin. If the window size is lower than 920px, then the height of the #sequence div shou ...

What is the best way to access a reference to the xgrid component in @material-ui?

Is there a way to obtain a global reference to the xgrid component in order to interact with it from other parts of the page? The current code snippet only returns a reference tied to the html div tag it is used in, and does not allow access to the compo ...

Avoid activating the panel by pressing the button on the expansion header

I'm facing a problem with the delete button on my expansion panel. Instead of just triggering a dialogue, clicking on the delete button also expands the panel. How can I prevent this from happening? https://i.stack.imgur.com/cc4G0.gif <v-expansion ...

SelectBoxIt jquery plugin can be applied after the completion of populating options in the select element with AngularJS

Utilizing AngularJS, I am dynamically populating a select box with the code below: <select ng-model="department" ng-options="dept as dept.name for dept in departmentList" class="fancy"> <option value="">-- select an optio ...

Transform XML to JSON format with Python by leveraging the lxml library along with XSLT operations

Currently, I am facing an issue while trying to convert XML to JSON using python3, lxml-library, and XSLT. Every time I run my code, it throws a XSLTParseError, leaving me confused about the next steps to take. Illustrative XML Snapshot: <SOAP-ENV: ...

Submitting a form via NextJS to an internal API

After reading through the Next.JS documentation, I came across an interesting point. Note: Instead of using fetch() to call an API route in getStaticProps, it's recommended to directly import the logic from within your API route and make necessary cod ...

What should be used for data fetching in Next.js: SWR or traditional fetch/axios along with useEffect?

I'm currently diving into the world of Next.js and I'm eager to showcase data based on user input queries. However, I'm uncertain if leveraging useSWR is the most suitable approach to tackle this challenge because I haven't come across ...

Extracting JSON Keys from an Array in C# without Using a Model

I possess a JSON document { "UniqueTitle": [ { "UniqueKey1": "Data", "UniqueKey2": "Data", "UniqueKey3": "Data", "UniqueKey4": "D ...

Updating state before and after making an API request

I have implemented an asynchronous function with prevState in my code. The purpose of using prevState is twofold: 1) updating a deeply nested object and 2) sending data to an API based on the current state. Asynchronous programming is utilized for the API ...

Deciphering JSON data containing a nested array in Swift 3

I came across this question discussing JSON parsing in Swift 3 and found it quite informative. However, I encountered a JSON structure with an array for the "weather" key (highlighted by the red arrow). While I was able to successfully parse other parts of ...