Converting a class into a cohesive JSON string within ASP.NET MVC

I have the following class:

[Serializable]
public class ApiRequestStatus :IEquatable<ApiRequestStatus>
{
    public static readonly ApiRequestStatus Failure =
                                            new ApiRequestStatus("Failure");
    public static readonly ApiRequestStatus Success =
                                            new ApiRequestStatus("Success");

    private string _status;

    private ApiRequestStatus(string status)
    {
        this._status = status;
    }

    public override string ToString()
    {
        return _status;
    }

    public bool Equals(ApiRequestStatus other)
    {
        return this._status == other._status;
    }
}

When this is serialized using the

System.Web.Script.Serialization.JavaScriptSerializer
I would like it to serialize as either the string "Failure" or "Success".

I have attempted to create a custom JavaScriptConverter, but this results in my object being rendered with zero or more properties depending on the

IDictionary<string, object>
I return.

For example, when I return an empty

IDictionary<string, object>
, my object appears as an empty JavaScript object: { }.

If I return

new Dictionary<string, object> { {"_status", status._status}}
, my object appears as { "_status" : "Success" }.

How can I serialize the object to only include the string value of its _status field?

Answer №1

Implement a ToJsonString() function in your class to handle serialization manually, specifically targeting the _status property.

For all other cases, simply serialize this (which can be inherited for organization) and return the result.

Answer №2

To resolve the issue, I found a solution by converting my ApiRequestStatus to an enum and utilizing the Json.NET serializer along with the JsonConverter attribute. However, I am curious to explore if a similar approach can be implemented using the JavaScriptSerializer.

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

Tips on incorporating redirect link to Material UI icon's onclick in React

I'm encountering some issues when trying to add a function to the VideocamOutlinedIcon on line 232. I want this function to include an onclick event that redirects the user to an external domain link in a new tab. Despite attempting various solutions, ...

I am looking to display multiple divs sequentially on a webpage using JavaScript

Looking to display a rotating set of alerts or news on my website. The goal is to show each news item for a certain number of seconds before moving on to the next one in line. However, I'm new to javascript and need help creating a code that will cont ...

Using PHP and JQuery to disable a button after the letter "U" is typed

I am looking for a way to disable the button when the term "U" (defined as Unable) appears. How can I achieve this? Below is the button in question: <input type="submit" class="form-control btn-warning" name="search" value="Search Data"></input& ...

Running a Blitz.js api handler triggers a Google Cloud Storage call failure with the message "error:0909006C:PEM routines:get_name:no start line"

When attempting to utilize @google-cloud/storage within a Blitz.js /api handler, I encounter the following error: error:0909006C:PEM routines:get_name:no start line at Sign.sign (internal/crypto/sig.js:110:29) at NodeCrypto.sign (C:\Users&bsol ...

Refresh the vue-owl-carousel following a dynamic data update

Utilized vue-owl-carousel with dynamic content <script> import carousel from 'vue-owl-carousel' export default { components: { carousel }, } <carousel :items="1"> <img v-for="(img, index) in images" ...

Waiting for Promise Js to be fulfilled

I've been exploring the use of Bluebird for handling promises in Node.Js. I have encountered a situation where I need a function to return only when a promise is fulfilled. The desired behavior can be illustrated by the following code snippet: functi ...

Dealing with errors in React by utilizing the setState function

Encountering an issue while trying to update the state of a single component. A warning message states: Each child in an array or iterator should have a unique "key" prop. The list was created within the state. The intention is to update the list upon c ...

I am looking to transfer information in CodeIgniter from a view utilizing AJAX post, handle that information in the controller, and then return the resultant array back to the view

I have been searching the entire internet, but unfortunately, I couldn't find a helpful solution. Any assistance would be greatly appreciated. Thank you in advance. MY HTML <div class="row"> I am unsure whether the form tag is required in my ...

Trigger Angular Animation when there is a modification in the DOM element's appearance or styling

I've been working on implementing a fade-in animation in my Angular App that triggers every time the background changes, but I'm facing some challenges with it. Here's the relevant code snippet: HTML: <div @fadeIn [style.backgroundImag ...

What is the method for assigning a different property type in a mongoose schema other than the one that is specified?

Looking for some advice on setting up a user profile schema in Mongoose for a forum. My goal is to have the user's forum title as an ObjectID referencing the Title schema. I have already established this part of the setup. However, my dilemma is that ...

Locate the selected radio button's label

There are 25 radio button groups on my page. Each group has a specific action that needs to be performed when a radio button is selected. In order to execute the correct action for each group, I require the NAME attribute of that particular radio group. ...

When using jQuery and Laravel, why does the element not appear when setting its display to block after receiving a response?

Trying to handle data (id) retrieved from the database and stored in a button, which appears in a modal like this: https://i.sstatic.net/i0boj.png There are buttons for "Add" and "Remove", but the "Remove" button is hidden. What I want to achieve: When ...

Utilizing JSON data to instantiate classes from a file

class Company: def __init__(self, company_id, name): self.company_id = company_id self.name = name In my programming project, I have a Python class called Company (as shown above). I am currently working on integrating companies into t ...

Using a JavaScript function to post the input value and then displaying it through PHP

I am striving to create an input field that will capture the value of what is typed and display it. The JavaScript function is designed to retrieve the value of the input box two seconds after the user stops typing and then post it. However, the issue lies ...

failure to properly assign a property during model update in mongoose

My BaseSchema contains logic that should set values for two properties when a new Model is created: schema.pre("save", function (next) { if (!schema.isNew) { this.createDate = new Date(); this.createBy = "kianoush"; } next(); }); If updating, ...

Having trouble clicking a button using Python and Selenium that triggers the `openWindow` function

I am attempting to interact with a button using Python Selenium WebDriver (Chrome). Here is the HTML code of the button: <button type="button" class="button blue" onclick="openWindow(LINK_HERE, 'idpage6')">Like</button> (I had to re ...

Developing New Arrays from JSON Responses using AngularJS

I have a function linked to the factory for controlling: fac.GetDailyCountersList = function () { return $http.get('/Data/GetDailyCountersList') } Within the controller, this is how the function is invoked: $scope.DailyCounters = null; Dai ...

Pulling JSON data from GitHub using Python and Streamlit

Hello everyone, first of all thank you for your assistance, I've been working on streamlit and Python, and now I'm looking to deploy everything on Heroku. This will be my initial experience with deploying an app on Heroku. My goal is to load JS ...

Instead of using `await asyncCall()`, try using `(await asyncCall())[0]`

After examining the Typescript code below, I'm curious to understand the rationale behind assigning myArray with (await asyncRPCCall())[0] instead of simply using await asyncRPCCall(). Why is the result placed inside () and why return only the first e ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...