From TypeScript to Java: transforming enums to JSON and back

As we develop an Angular2 app (utilizing Angular 13 and Typescript 4.5.5), we heavily rely on string enums, structured like so:

    export enum Language {
       de = "German",
       fr = "French",
       it = "Italian",
       en = "English"
     }

    export class Request {
       language: Language = Language.de;
       ... // other properties with enum values
     }

The value in the enum (e.g. "Italian") represents what should be shown to users, such as in a drop-down menu. The key in the enum (e.g. 'it') is what we want to store in the backend database when submitting data to our Java-based REST service.

On the server side, we have a corresponding Java enum setup as follows:

public enum Language {
    de, fr, it, en
}

@Entity
public class Request {
    @Enumerated(EnumType.STRING)
    private Language language;

    ... // other persistent properties
}

The challenge arises when sending data to the backend service - TypeScript serializes the enum to JSON using its value. This causes the service to receive "Italian" instead of "it," leading to issues mapping to the Java enum.

Likewise, when fetching data from the server to display in the Angular interface, the service sends "it" rather than "Italian." Consequently, deserializing JSON back into the TypeScript enum fails.

Is there a way to instruct TypeScript to use the enum key for both serialization and deserialization to/from JSON?

Moreover, can you recommend an approach that effectively separates the user-facing display value from the technical storage value in the database?

Answer №1

Unfortunately, I am unable to leave a comment at the moment, but I wanted to respond with some helpful information:

It seems like you may be using either Angular Material or PrimeNG for your GUI development.

Both options allow you to set the displayed value (e.g., "Italian") to a different variable than the value stored (e.g., "it") for components like dropdowns.

For PrimeNG, you can refer to the documentation here: [https://www.primefaces.org/primeng-v11-lts/#/dropdown][1]

<p-dropdown [options]="languages" [(ngModel)]="selectedlanguage" optionLabel="nameFull" optionValue="nameShort"></p-dropdown>

And for Angular Material, you can check out this link: [https://material.angular.io/components/select/overview#getting-and-setting-the-select-value][1]

<mat-select [(ngModel)]="selectedlanguage" name="language">
      <mat-option *ngFor="let language of alllanguages" [value]="language.nameShort">
        {{language.nameLong}}
      </mat-option>
</mat-select>

In your .js file:

interface Languages {
  name: string;
  namelong: string;
}
string selectedlanguage;
Languages alllanguages[] =  // an array with all your values.

I hope this explanation is useful to you :)

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

Guide on changing the orientation of points generated with Graphics or Graphics2D in relation to the central point

Greetings! Currently, I am immersed in working on graphics using Java Swing. My goal is to manipulate the points within the jpanel by simultaneously flipping them up and down based on the center point of the jpanel. I have attempted to find a method to e ...

Error: Name 'AudioDecoder' could not be located

In my current project using React and TypeScript with Visual Studio Code 1.69.2 and Node 16.15.1, I encountered an issue. I am attempting to create a new AudioDecoder object, but I keep getting an error message stating "Cannot find name 'AudioDecoder ...

Regex for capturing all text, including special unicode punctuation marks

I am attempting to locate specific text that may contain unicode characters, including special punctuation such as (\u0085 in Java). When I use the following code: Matcher testMatcher = Pattern.compile("(.+)", Pattern.UNICODE_CHARACTER_CLASS).matche ...

Form with checkboxes in a Next.js and Typescript application

I am currently working on a project using Next.js and Typescript. I have implemented a form in this project, which is my first experience with Typescript and checkbox types. However, I am encountering difficulties in retrieving all checkbox values, adding ...

Is it possible for a conditional type in TypeScript to be based on its own value?

Is it possible to use this type in TypeScript? type Person = { who: string; } type Person = Person.who === "me" ? Person & Me : Person; ...

Customize your Visual Studio Code Emmet preferences by adding Stylus, a CSS preprocessor

While the default Emmet snippets in Visual Studio Code are effective in CSS, HTML, LESS, and SASS files, I personally prefer using Stylus for my CSS coding. Unfortunately, these snippets do not seem to work in VS Code when using Stylus. I have tried insta ...

bespoke session with Next.js using Next-Auth

I encountered an issue while migrating my JS file to TSX. What I am trying to do is sign in with credentials and customize the session user to my user data. // api/auth/[...nextauth].js import NextAuth from "next-auth"; import Providers from &qu ...

Rails application encountering a problem with JSON data retrieval

Encountering an issue with Rails and Devise where I get logged out every time I request a .json extension file. For instance, if I visit /tables.json to view table data, it shows up fine. But when I navigate back to the root folder, I find myself logged o ...

Ensuring Mongoose Schema complies with an external API

My database schema includes a mongoose User schema with the following structure: const User: Schema = new Schema({ // some other fields email: {type: String, unique: true, require: true, validate: [myValidator, 'invalid email provided'], // some ...

The enum cannot be assigned a type of 'string | null'

Within my ProductGender enum, I have: enum ProductGender { Men, Women, } In my getProducts service: public getProducts( gender: ProductGender, category: ProductCategory ): Observable<IProductInterface[]> { return this.httpPro ...

Tips on transforming Angular 2/4 Reactive Forms custom validation Promise code into Observable design?

After a delay of 1500ms, this snippet for custom validation in reactive forms adds emailIsTaken: true to the errors object of the emailAddress formControl when the user inputs [email protected]. https://i.stack.imgur.com/4oZ6w.png takenEmailAddress( ...

Creating a Jira-inspired table layout in Angular by embedding components in a structured format

I'm attempting to recreate the functionality of Jira where I can create a "gadget" that can be added to a board, resized, moved, and deleted. (For those unfamiliar with why this might be useful, think of gadgets like the "Gantt" gadget. You can add a ...

Troublesome php ajax application failing to function

Despite creating a simple PHP and AJAX application, I am encountering issues and unable to identify the root cause. Below is my code snippet: <?php $grId = $_GET["groupId"]; $limit = $_GET["limit"]; if ($limit <= 0) { $limit = 10; } $serverna ...

What is the best way to periodically take a photo using a camera service?

My goal is to periodically capture a photo from a camera service and send it through a socket to a server application (desktop software). I attempted to achieve this with the code below, but it only captures one image and does not continue to capture. Acc ...

A guide to efficiently removing an element in Angular using TypeScript by considering certain properties

I need help removing an element from an array based on any property such as its key, name, or email. HTML <tr *ngFor="let person of persons;" (click)="remove(person.key)"> <td>{{person.key}}</td> <td>{{person.name}}</td> ...

Unable to debug json.loads() code using pdb

I am curious to understand the inner workings of converting a JSON string to a Python dictionary using json.loads() For example: import json s = '{"a": 1, "b": 2}' # input json string d = json.loads(s) # output dictionary object To dive de ...

What is the best way to retrieve a specific value from a multi-dimensional JSON object array?

I'm struggling to retrieve a value from the JSON object below array(3) { [0]=> object(stdClass)#1 (11) { ["Group"]=> string(2) "18" ["GroupName"]=> string(8) "Wireline" ["Region"]=> string(2) "15" ["RegionName"]=> string(8) "Atlantic" ...

Having trouble with converting parseJSON to JSON response in jQuery AJAX

I am just starting to learn about AJAX with jQuery. Below is the JSON response I have: [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}] Here is my AJAX file: function(result){ $('#resdiv').htm ...

Monitor the change in values upon pressing the submit button on Angular

I am currently working with an edit form that contains data in the input fields. <ng-form #infoForm="ngForm" novalidate> <div> <label for="firstName">First Name :</label> <input type=" ...

What is the best way to showcase an error message returned as a JSON object from a servlet class using JavaScript/Dojo?

One of my clients has requested a file upload feature through dojo.io.iframe in order to pass binary data to a web application on a websphere app server. The servlet class within the web app then makes a rest web service call to an external system, creatin ...