0

Say I have the following enum:

public enum Test
{
    item1 = 1,
    item2 = 2,
    item3 = 3
}

I add all those enums to a list using JsonConvert.SerializeObject. I then have a JSON string as follows:

["item1","item2","item3"]

I then want to Deserialize the JSON back into a list of the enums. So:

List<Test> list = JsonConvert.DeserializeObject<List<Test>>(json string);

This works, great.

However, if I remove one of the enum items after the list has been serialized I get an error.

So, my enum becomes:

public enum Test
{
    item1 = 1,
    item3 = 3
}

I now get an error on this line.

List<Test> list = JsonConvert.DeserializeObject<List<Test>>(json string);

The error is:

Error converting value "item2" to type 'Test'

How can I get round this?

I've tired added the following JsonSetting but this made no difference.

new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.Auto
                    }
Sun
  • 4,458
  • 14
  • 66
  • 108

2 Answers2

1

You can just ignore this kind of errors (in example I ignore every error, but you will figure it out for your case):

var result = JsonConvert.DeserializeObject<List<Test>>(json string, new JsonSerializerSettings
    {
        Error = HandleDeserializationError
    });

public void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
    var currentError = errorArgs.ErrorContext.Error.Message;
    errorArgs.ErrorContext.Handled = true;
}
eocron
  • 6,885
  • 1
  • 21
  • 50
0

This is part of how enums work in C#, it happens because the enums are defined at compile time and and the deserializer can't figure out what "item2" should be. As Peter asked, what would expect to happen if you didn't get an error?

If you expect your enum values to change frequently, you may want to simulate an enum by using a class that only has named string constants instead. That will allow you some wiggle room for enum values being added/removed, but you'll still need to consider how your program will deal with values it hasn't encountered before!

Edit: On seeing your expectation, you could first deserializing your JSON to a string array, then iterate through your result and tryParse() each string, adding each valid result to the list (or using linq)

Thorin Jacobs
  • 290
  • 2
  • 9
  • Sorry, I forgot to add that the enum values are also set in the definition. – Sun Mar 02 '18 at 17:00
  • It response to your edit, I have considered that option. It may be my only option for this. – Sun Mar 02 '18 at 17:03