JSON: Serializing types derived from IEnumerable

前端 未结 2 404
后悔当初
后悔当初 2021-01-13 07:04

JavaScriptSerializer serializes types derived from IEnumerable as JavaScript arrays. It convenient for arrays and lists but in some cases I need to serialize properties decl

2条回答
  •  一个人的身影
    2021-01-13 08:09

    Check out JSON.NET. I've used it on a couple of projects and it makes JSON serialization and deserialization a lot easier. It will serialize most objects with a single method call, and also lets you have a finer-grained control over the serialization with custom attributes.

    Here's a sample from the author's website:

    Product product = new Product();
    
    product.Name = "Apple";
    
    product.Expiry = new DateTime(2008, 12, 28);
    
    product.Price = 3.99M;
    
    product.Sizes = new string[] { "Small", "Medium", "Large" };
    
    string json = JsonConvert.SerializeObject(product);
    
    //{
    
    //  "Name": "Apple",
    
    //  "Expiry": new Date(1230422400000),
    
    //  "Price": 3.99,
    
    //  "Sizes": [
    
    //    "Small",
    
    //    "Medium",
    
    //    "Large"
    
    //  ]
    
    //}
    
    
    
    Product deserializedProduct = JsonConvert.DeserializeObject(json);
    

提交回复
热议问题