Converting enums to numbers through JSON serialization

In my C# backend, I have enumerated settings with unique numbers assigned to each.

public enum Settings
{
    Setting1 = 1,
    Setting2 = 2,

    //...
}

To send these settings to the client through WebAPI, I use a dictionary structure.

public MyModel
{
    public Dictionary<Settings, string> MySettings { get; set; }

    //...other properties...
}

The issue arises when referencing this Enum in TypeScript. The problem lies in WebAPI converting the enum values to strings instead of numbers. However, I want to maintain the type of the dictionary as

Dictionary<Settings, string>
and not switch it to Dictionary<int, string>.

Is there a way to achieve this using attributes?

Answer №1

You have the option of creating a private or protected property that can be customized to suit your needs. Alternatively, you can implement standard get/set methods and make them public.

public class MyModel
{
    public Dictionary<int, string> MySettings { get; set; }

    //An alternative approach.
    private Dictionary<Settings, string> MyBetterSettings
    {
        get { return MySettings.ToDictionary(setting => (Settings) setting.Key, setting => setting.Value); }
        set { MySettings = value.ToDictionary(setting => (int) setting.Key, setting => setting.Value); }
    }

    //Straightforward C# 6 methods
    public Dictionary<Settings, string> GetSettings => MySettings.ToDictionary(setting => (Settings) setting.Key, setting => setting.Value);
    public void SetSettings(Dictionary<Settings, string> settings) => MySettings = settings.ToDictionary(setting => (int)setting.Key, setting => setting.Value);
}

While not perfect, it provides a good compromise by eliminating concerns about serialization changes.

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

Replacing text in a file using AJAX, JS, and PHP and sending it to a PHP file with successful attribute included

Within my code, there is a button identified by the ID genPDF that triggers the following function upon being clicked: $('#genPDF').click(function () { var str = "headingText=" + jQuery("#headingText").val(); $.ajax({ url: &apo ...

Is it Possible for the Number Array Type to Not Be Recognized as an Array?

export class ... { single: any[] = []; multi: any[] = []; view: number[] = [700, 400]; ... <Removed for brevity> } Error Message: It says 'Type 'number[]' is not assignable to t ...

Dealing with errors from APIs in a React TypeScript application

Currently, I am in the process of learning React and Typescript by creating a demo application. This app sends a request to the API located at in order to retrieve postcode information and display details about a specific location based on the entered pos ...

I am looking to dynamically print countries from an array in my code based on the selected option

I'm in need of some simple code assistance. I want to display a list of countries that correspond to a selected letter, but I'm struggling to do so dynamically at the moment. For example, if I select the letter A from a dropdown menu, I want the ...

Tips for converting JSON data from PHP into a string constant

Is there a way to dynamically pass the JSON contents of a PHP file to 'the_json' instead of statically putting the values? Here is my code: try { String the_json = "{'profiles': [{'name':'john', 'ag ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Divide various text files into separate arrays using jq

I'm faced with a challenge involving files containing multiple key value pairs that I need to convert into arrays. Allow me to demonstrate this with some examples from the file contents: # cat content/1.yaml time: "2020-09-14T22:33:40Z" id: ...

The Google Books API initially displays only 10 results. To ensure that all results are shown, we can implement iteration to increment the startIndex until all results have

function bookSearch() { var search = document.getElementById('search').value document.getElementById('results').innerHTML = "" console.log(search) var startIndex = I have a requirement to continuously make Ajax calls ...

Executing a function in Angular depending on the values emitted by two distinct observables

As someone who is relatively new to Angular (6 months), I am facing a challenge with my code. Currently, I have two observables that are working independently of each other: this.siteService.siteChanged$ .pipe(takeUntil(this.disconnect$)) .subscribe(_ ...

An effective way to define the type of a string property in a React component using Typescript

One of the challenges I'm facing is related to a React component that acts as an abstraction for text fields. <TextField label="Enter your user name" dataSource={vm} propertyName="username" disabled={vm.isSaving} /> In this set ...

What is the proper approach to implementing user functionality in MSMQ?

Hey there! I'm not quite sure if I chose the right title for this, but let's give it a shot anyway. Currently, I have a system that handles over 720,000 users, and I haven't utilized queues yet. I'm looking to start using them. Let me ...

Receiving a 400 status code indicating a Bad Request upon posting a Json object

Currently, I am attempting to send a post request to a WCF service using an email object that contains attributes for subject and body. However, when making an ajax call, I am encountering a 400 Bad Request error. Below is the code snippet I am using, bu ...

Extract JSON data from an API using PHP and then convert it into HTML format using Javascript

I'm brand new to the world of coding. Currently, I am utilizing PHP to fetch a JSON response from an API. Within this JSON data are Titles and corresponding URLs to various web pages. A snippet of the JSON response can be found at the conclusion of t ...

Steps to attach a trigger to an UpdatePanel using a UserControl

Our Default.aspx page contains an updatepanel where we load ASCx user controls. We are currently looking to dynamically add triggers for the updatepanel from our usercontrols. Are there any methods available for achieving this? If yes, what would be the b ...

JSONError: Missing gps value?

This is the method I use to create a JSON response. if ($tag == 'test') { $json = array(); $json["gps"] = array(); $result = mysql_query("SELECT lats,longs,types FROM wrdgps"); if ($result) { wh ...

"Encountering problems with the form tag with runat server attribute when creating user controls dynamically

I am currently working on generating a user control that includes a label, dropdown menu, and text box dynamically so that I can easily set the value of the label. However, I encountered an issue with the dropdown and textbox because they require a form ta ...

Using JavaScript to access array INDEX values sequentially

I have created a Stacked Bar chart using the Js library dhtmlx, and here is the generated output: The JSON data is structured as follows: var data = [ { "allocated":"20", "unallocated":"2", "day":"01/01/2014" }, { "allocated":"12", "unallocated": ...

Utilizing TypeScript to define React interfaces

How can I effectively utilize two interfaces for the same object? For instance: interface interfaceOne { id: string color: string } interface interfaceTwo { id: string numb: number } I have an Item component that is designed to receive an item ob ...

C++: When it comes to design decisions, is using an enum the best choice here

What is the most efficient method in C++ to divide the alphabet into 7 groups so that I can easily determine which group a character belongs to later on? I could come up with my own ways of achieving this, but I prefer to follow the standard approach whe ...

Tips for fully accessing a website with javascript enabled through an android service

I've been attempting to extract data from a website node that includes JavaScript. In VB .NET, the code I typically use is as follows: Dim listSpan As IHTMLElementCollection = bodyel.getElementsByTagName("span") For Each spanItem As IHTMLElement In ...