How to handle conversion from string to enum when string starts with number in Json.Net

I get json from a server, which I convert to an object using Json.Net. For one member I use StringEnumConverterthat works great.

However, all of a sudden, the server decided to use strings that could also start with a number, which leads to a JsonSerilizationException - obviously because enumerations cannot start with a number in .Net.

Now I am trying to find a solution to handle this. My first approach was to add "_" when reading Json (so my enumerations in the code will have the beginning _ when the number follows) and when writing json I delete start _ (if the number is next). To do this, I copied StringEnumConverterinto my namespace and tried to change the corresponding part in WriteJsonand methods ReadJson. However, I cannot use it StringEnumConverter, as there are other dependencies that I cannot access in my own namespace.

Is there an elegant solution to this problem?

+4
source share
2 answers

You can create JsonConverterand crop numbers in front.

public class Json_34159840
{
    public static string JsonStr = @"{""enum"":""1Value"",""name"":""James"",""enum2"":""1""}";

    public static void ParseJson()
    {
        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Converters = new List<JsonConverter> { new EnumConverter() }
        };

        // Later on...
        var result = JsonConvert.DeserializeObject<JsonClass>(JsonStr);
        Console.WriteLine(result.Enum);
        Console.WriteLine(result.Enum2);
        Console.WriteLine(result.Name);
    }
}

public class EnumConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var str = value.ToString();
        if (Regex.IsMatch(str, @"^_"))
        {
            writer.WriteValue(str.Substring(1));
        }
        else
        {
            writer.WriteValue(str);
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var value = reader.Value.ToString();
        if (Regex.IsMatch(value, @"^\d+$"))
        {
            return Enum.Parse(objectType, value);
        }

        if (Regex.IsMatch(value, @"^\d+"))
        {
            value = "_" + value;
        }

        return Enum.Parse(objectType, value);
    }

    public override bool CanConvert(Type objectType)
    {
        //You might want to do a more specific check like
        //return objectType == typeof(JsonEnum);
        return objectType.IsEnum;
    }
}

public enum JsonEnum
{
    _0Default,
    _1Value
}

public class JsonClass
{
    public string Name { get; set; }
    public JsonEnum Enum { get; set; }
    public JsonEnum Enum2 { get; set; }
}

, .

EDIT: ​​ : D

+3

string, ( ) .

+1

Source: https://habr.com/ru/post/1619061/


All Articles