skip to Main Content

Basically I have a frontend which uses Angular (And Node.JS built-in) to send requests to a remote back-end application built in C# and ASP.NET.

In both the frontend and the back-end I have the following enums declared:

public enum UserType
{
   New, 
   Old,
   Returning
}

In the frontend the user selects their option and it sends within a wider JSON object as:

"UserTypeField" : "New",

I have also tried:

"UserTypeField" : "UserType.New",

In the backend I have a model class with the field:

public UserType UserFactor { get; set;}

The problem I am having is that all of the other fields within the JSON get set. However, after adding this field in the backend and sending an ENUM as part of the POST request I receive an error response:

UserFactor":["The JSON value could not be converted to UserType. Path: $.UserFactor | LineNumber: 0 | BytePositionInLine: 341."]}}

I am struggling to figure out how to send the enum as a string. I know I could use an integer, but for this project I am unable to due to the way in which the rest of the application works.

2

Answers


  1. Your property names do not match: UserTypeField in the front-end, UserFactor in the back-end. Make that change and see if the implicit conversion works.

    If not, then you’ll have to define a setter for your back-end property that will handle the enum parsing appropriately.

    Login or Signup to reply.
  2. You have to fix the property name. This code works for me

    using Newtonsoft.Json;
    
    var json="{"UserTypeField" : "New"}";
            
    UserType userTypeField = 
               JsonConvert.DeserializeObject<UserFactor>(json).UserTypeField; // New
        
    
    public class UserFactor
    {
        public UserType UserTypeField { get; set;}
    }
    
    public enum UserType
    {
        New,
        Old,
        Returning
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search