Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Net (8.0) Error creating StringEnumConverter on Mono 4.5 Mac

I am having trouble understanding the issue I am getting with Json.Net on Mac. I am trying to serialize/deserialize objects like the one below.

The code runs without issues on Windows but generates a Newtonsoft.Json.JsonException "Error creating StringEnumConverter" on Mac (also shown in the image). I am hoping someone does see something in the code or error message that could point me in the right direction. The object contains many more fields but the error sounds like it has something to do with the enums. I am building in Xamarin 6 / Mono .Net 4.5 and I am using Json.Net 8.0.3 for .Net 4.5. Any help greatly appreciated.

Edit 1: Removing the JsonConverter(typeof(StringEnumConverter)) decoration avoids the exception - however, enums are serialized as integers again.

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Lib
{
    [DataContract(IsReference = true)]
    public class Construction : LibraryComponent
    {
        public Construction() { }
        public override string ToString() { return Serialization.Serialize(this); }

        [DataMember]
        public string Construction { get; set; } = "defaultConstruction";

        ...

        [DataMember, JsonConverter(typeof(StringEnumConverter)), DefaultValue(InConvAlgo.TARP)]
        public InConvAlgo SurfaceConvectionModelInside { get; set; } = InConvAlgo.TARP;

        [DataMember, JsonConverter(typeof(StringEnumConverter)), DefaultValue(OutConvAlgo.DOE2)]
        public OutConvAlgo SurfaceConvectionModelOutside { get; set; } = OutConvAlgo.DOE2;

        ...

        [DataMember, DefaultValue(1)]
        public int Priority { get; set; } = 1;
    }

    public enum InConvAlgo { Simple, TARP, TrombeWall, AdaptiveConvectionAlgorithm };
    public enum OutConvAlgo { DOE2, TARP, MoWiTT, SimpleCombined, AdaptiveConvectionAlgorithm }; //  DOE-2,  

}

enter image description here

like image 843
timkado Avatar asked Sep 12 '25 20:09

timkado


2 Answers

StringEnumConverter doesn't have its own public constructor which is needed by code. You can use JsonStringEnumConverter which provides public constructor.

replace: [JsonConverter(typeof(StringEnumConverter))] ====> [JsonConverter(typeof(JsonStringEnumConverter))]

And it will work.

like image 75
Jai Avatar answered Sep 14 '25 10:09

Jai


I had the same issue with mono.

A simple workaround which works for me was to create a class that inherit from StringEnumConverter and use it.

That avoid you from copying the source code of this converter (Json.net has a lot of "utils" class).

No more issue after that.

like image 36
Daztane Avatar answered Sep 14 '25 11:09

Daztane