/ Serialização JSON condicional usando c # - c #, json, serialização

Serialização JSON condicional usando c # - c #, json, serialização

Eu tenho uma classe que eu serializar para JSON em c # epostar em um serviço da Web RESTful. Eu tenho um requisito que, se um campo for preenchido, outro campo não estará presente. Os erros de serviço se ambos os campos forem serializados no objeto JSON. Minha turma parece com isso:

    [DataContract(Name = "test-object")]
public class TestObject
{
[DataMember(Name = "name")]
public string Name { get; set; }

// If string-value is not null or whitespace do not serialize bool-value
[DataMember(Name = "bool-value")]
public bool BoolValue { get; set; }

// If string-value is null or whitespace do not serialize it
[DataMember(Name = "string-value")]
public string StringValue { get; set; }
}

Como observado nos comentários, se StringValue tiver um valor, não coloque BoolValue no objeto JSON. Se StringValue estiver em branco, não coloque em StringValue, mas coloque em BoolValue.

Eu encontrei como fazer isso com serialização XML, mas não consigo encontrar uma maneira que isso funciona com a serialização JSON. Existe serialização JSON condicional em C #?

Respostas:

1 para resposta № 1

Parece que você está usando o DataContractJsonSerializer. Nesse caso, você pode:

  1. Desative a serialização direta de suas propriedades com o atributo [IgnoreDataMember].
  2. Criar proxy string e bool? propriedades para serialização que retornam null quando não devem ser serializadas. Estes podem ser private.
  3. Conjunto [DataMember(EmitDefaultValue=false)] nessas propriedades de proxy para suprimir a saída de nulos.

Portanto:

[DataContract(Name = "test-object")]
public class TestObject
{
[DataMember(Name = "name")]
public string Name { get; set; }

[IgnoreDataMember]
public bool BoolValue { get; set; }

[IgnoreDataMember]
public string StringValue { get; set; }

bool ShouldSerializeStringValue()
{
return !String.IsNullOrWhiteSpace(StringValue);
}

// If string-value is not null or whitespace do not serialize bool-value
[DataMember(Name = "bool-value", EmitDefaultValue=false)]
bool? SerializedBoolValue {
get
{
if (!ShouldSerializeStringValue())
return BoolValue;
return null;
}
set
{
BoolValue = (value ?? false); // Or don"t set it at all if value is null - your choice.
}
}

// If string-value is null or whitespace do not serialize it
[DataMember(Name = "string-value", EmitDefaultValue=false)]
string SerializedStringValue {
get
{
if (ShouldSerializeStringValue())
return StringValue;
return null;
}
set
{
StringValue = value;
}
}
}

Aliás, isso também funcionará com Json.NET, que respeita atributos do contrato de dados.