Voglio serializzare un tipo enum, in modo che restituisca una matrice con l'enumerazione come un oggetto che contiene sia il "valore", "nome" e un'annotazione dati valore. Ho bisogno di aiuto con la serializzazione. Ecco quello che ho fatto finora: L'enum:serializzazione Json.NET personalizzata di un tipo enum con annotazione dati
public enum Status
{
[Display(Name="Active status")]
Active = 1,
[Display(Name = "Deactive status")]
Deactive = 2,
[Display(Name = "Pending status")]
Pending = 3
}
L'oggetto DTO che dovrebbe essere serializzato:
public class ProjectDto
{
public Type StatusEnum { get; set; }
public Status CurrentStatus { get; set; }
}
Assegnazione di valori:
var project = new ProjectDto
{
CurrentStatus = Status.Active,
StatusEnum = typeof (Status)
};
var output = JsonConvert.SerializeObject(project);
per ottenere i valori dall'enum che utilizzo:
Enum.GetNames(typeof(Status)) //To get the names in the enum
Enum.GetValues(typeof(Status)) //To get the values in the enum
Per ottenere il valore del nome dei dati di annotazione è un po 'più complicato, ma ho trovato aiuto in questo articolo: http://geeksharp.com/2011/11/02/power-up-your-enumerations/ Hanno creato un metodo di supporto che otterrà il valore scritto nella annotazioni dati utilizzando:
public static string GetAttributeValue<T>(this Enum e,
Func<T, object> selector) where T : Attribute
{
var output = e.ToString();
var member = e.GetType().GetMember(output).First();
var attributes = member.GetCustomAttributes(typeof(T), false);
if (attributes.Length > 0)
{
var firstAttr = (T)attributes[0];
var str = selector(firstAttr).ToString();
output = string.IsNullOrWhiteSpace(str) ? output : str;
}
return output;
}
E è possibile ottenere il valore utilizzando:
.GetAttributeValue<DisplayAttribute>(y => y.Name)
uscita dovrebbe essere qualcosa di simile
{
statusEnum: [
{ "value": "1", "name": "Active", "label": "Active status" },
{ "value": "2", "name": "Deactive", "label": "Deactive status" },
{ "value": "3", "name": "Pending", "label": "Pending status" }
],
currentStatus: { "value": "1", "name": "Active", "label": "Active status" }
}
come accennato Ho bisogno di aiuto per creare il serial JSON.NET personalizzato e deserializzare per ottenere l'output desiderato. Qualsiasi aiuto sarebbe aperto.
La proprietà 'CurrentStatus' è in realtà una matrice? Inoltre, come è 'StatusEnum', che è di tipo' System.Type', essendo serializzato su un oggetto simile? –
Scusate buona cattura. Mi sono perso il fatto che avevo confuso statusEnum e currentStatus sull'output, ora risolto.statusEnum dovrebbe rappresentare il tipo di enum di stato con tutti i suoi valori mentre currentStatus dovrebbe rappresentare il singolo valore enum che è stato "selezionato" –