Matias Barrios
Matias Barrios

Reputation: 5056

Deserializing a C# class with NetwonSoft.Json leaves a partial Json string as response

I have the following class and enum:

public class Email   
{
    string Address;
    EEmailType Type;
}

public enum EEmailType 
{
    Primary,
    Alternative
}

The problem I'm seeing is that I have a handler where I return a collection of these objects as a json response.

The response is coming fine and includes the email address for all the emails I can fetch, but the email type is not returned.

When I get the response I instead get :

[
  {
    address : "[email protected]"
  }
]

So the type of email is nowhere to be seen. Also, in the mapper where I'm building this collection I call a function that converts a string we receive from the backend to an enum:

public EEmailType convertToEnum(string input) 
{
  switch(input) 
  {
      case "Primary" :
           return EEmailType.Primary;
     ......... *and so on*
  }
}

But if instead of using my function I directly hardcode a value then it does show up in the json string which is returned:

emails.Add(
new Email {
    Address : response.address,
    Type : convertToEnum(response.type) <----- THIS DOES NOT WORK
});

emails.Add(
new Email {
    Address : response.address,
    Type : EEmailType.Primary <----- THIS WORKS FINE
});

What am I doing wrong here?

Upvotes: 1

Views: 92

Answers (1)

Matias Barrios
Matias Barrios

Reputation: 5056

Well, I fixed this issue. Believe or not I started an issue in Carter framework repo for something which I thought might be unrelated but as I implemented it it also corrected the issues I was seeing with vanishing fields.

This is the issue in question : https://github.com/CarterCommunity/Carter/issues/204

I created that class with that exact name in the root of my project and Carter automagically picked it up.

Now all problems are gone.

Thanks everyone for your answers!

Upvotes: 1

Related Questions