2009-09-07 22 views

cevap

12

benim için çalıştı çözüm şu şekildedir:

tefrika sınıf ve özellikleri süslenecek:

[DataContract] 
public class MyDataClass 
{ 
    [DataMember(Name = "LabelInJson", IsRequired = false)] 
    public string MyProperty { get; set; } 
} 

IsRequired anahtar öğe oldu.

gerçek seri DataContractJsonSerializer kullanılarak yapılabilir: Eğer kolay çözümü ile gitmek isterseniz,

public static string Serialize<T>(T obj) 
{ 
    string returnVal = ""; 
    try 
    { 
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     serializer.WriteObject(ms, obj); 
     returnVal = Encoding.Default.GetString(ms.ToArray()); 
    } 
    } 
    catch (Exception /*exception*/) 
    { 
    returnVal = ""; 
    //log error 
    } 
    return returnVal; 
} 
+6

DataContractJsonSerializer için DataMember – FinnNk

4

JavaScriptConverter uygulayabilir ve JavaScriptSerializer yöntemini kullanarak kayıt edebilirsiniz.

4

Json.NET otomatik null veya varsayılan değerleri hariç seçenekleri vardır.

+13

OP json.net değil JavaScriptSerializer hakkında sorular soruyordu. –

+5

@JustinR. Json.NET'in yazarı gibi görünüyor ve bu yüzden muhtemelen – Steve

27

Bilginize, burada JavaScriptSerializer ile JavaScriptConverter uygulamasını kullanarak bunu gerçekleştirmek için kullanılan budur:

sonra
private class NullPropertiesConverter : JavaScriptConverter 
    { 
     public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) 
     { 
      throw new NotImplementedException(); 
     } 

     public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) 
     { 
      var jsonExample = new Dictionary<string, object>(); 
      foreach (var prop in obj.GetType().GetProperties()) 
      { 
       //check if decorated with ScriptIgnore attribute 
       bool ignoreProp = prop.IsDefined(typeof(ScriptIgnoreAttribute), true); 

       var value = prop.GetValue(obj, BindingFlags.Public, null, null, null); 
       if (value != null && !ignoreProp) 
        jsonExample.Add(prop.Name, value); 
      } 

      return jsonExample; 
     } 

     public override IEnumerable<Type> SupportedTypes 
     { 
      get { return GetType().Assembly.GetTypes(); } 
     } 
    } 

ve kullanmak için:

var serializer = new JavaScriptSerializer(); 
    serializer.RegisterConverters(new JavaScriptConverter[] { new NullPropertiesConverter() }); 
    return serializer.Serialize(someObjectToSerialize); 
+2

'da false olarak EmitDefaultValue değerini ayarlamanız gerekiyor. Ayrıca alanların da eksik olmasını istiyorsanız, kodun –

+0

olduğunu merak etmelisiniz. önceki yorum hakkında konuşuyordu: http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c –

+0

Bunu biraz daha hızlı bir şekilde yapabilirsiniz. Önce ignoreProp'u kontrol etmek ve yanlış olmadığı sürece değeri almamak. – Brain2000

1

Bu kod, sayısal türleri yararına

private class NullPropertiesConverter : JavaScriptConverter 
    { 
     public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) 
     { 
      throw new NotImplementedException(); 
     } 

     public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) 
     { 
      var jsonExample = new Dictionary<string, object>(); 
      foreach (var prop in obj.GetType().GetProperties()) 
      { 
       //this object is nullable 
       var nullableobj = prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>); 
       //check if decorated with ScriptIgnore attribute 
       bool ignoreProp = prop.IsDefined(typeof(ScriptIgnoreAttribute), true); 

       var value = prop.GetValue(obj, System.Reflection.BindingFlags.Public, null, null, null); 
       int i; 
       //Object is not nullable and value=0 , it is a default value for numeric types 
       if (!(nullableobj == false && value != null && (int.TryParse(value.ToString(), out i) ? i : 1) == 0) && value != null && !ignoreProp) 
        jsonExample.Add(prop.Name, value); 
      } 

      return jsonExample; 
     } 

     public override IEnumerable<Type> SupportedTypes 
     { 
      get { return GetType().Assembly.GetTypes(); } 
     } 
    } 
0

blok boş ve varsayılan (0) değerindedir Bunu google'da bulanlar, null'ların Newtonsoft.Json

ile yerel olarak atlanabileceğini unutmayın.
İlgili konular