简体   繁体   中英

C# Possible To Serialise Enum description instead Enum value With Json

I have the situation where I am receiving a response from two different web services. The two responses are identical in structure, but have different parent namespaces. What I am trying to do is convert these responses into a standard class I can then pass out to the parent object. I figured the simplest way was to Serialize the incoming object to Json, and then Deserialize the object into my standard object. This keeps my processing code rather simple

var jsonString = JsonConvert.SerializeObject(serviceResponse.Results);
var commonObject = JsonConvert.DeserializeObject<StandardResult>(jsonString);

And for the most part this is working. However I'm expanding the StandardResult object I've discovered a bit of a problem.

One of the properties of the object is a class with the following properties:

public class EntryDetailType
{
public string EntryNumber {get; set;}
public string EntryText {get; set;
public int Item {get; set;}
}

The issue is that Item can actually be one of two different enums in the incoming data. So although the conversion is correctly putting the enum's value in Item I have no idea which enum that value refers to. I'm not at this stage using a JsonConverter class as the object is very large and I wanted to avoid that if possible.

Is there a method of being able to get the enum's description instead of the value as part of this process, or am I going to be forced to write my own json converters? Please bear in mind that the EntryDetailType class is not in my project. It is the return type from a web service that has been added via a wsdl document.

Well, if the class EntryDetailType really has a property named Item of type int , it is not possible to infer which name representation value of the enum you have.

But, if this class has a property Item of any enum type, then it is as easy as serializing to Json using the built-in StringEnumConverter as the second parameter of the SerializeObject method:

var jsonString = JsonConvert.SerializeObject(serviceResponse.Results, new Newtonsoft.Json.Converters.StringEnumConverter()); 

ps: I'm assuming you are using the Json.NET from NewtonSoft.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM