JSON: Serializing types derived from IEnumerable

前端 未结 2 377
后悔当初
后悔当初 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 07:59

    You could try this:

    var items = new[] { "aaabbb", "abcd", "bdsasd", "bsdqw" };
    var data = (from x in items
                group x by x[0] into g
                select new
                {
                    Key = g.Key,
                    Value = g
                }).First();
    var serializer = new JavaScriptSerializer();
    var serialized = serializer.Serialize(data);
    

    or if you prefer:

    var items = new[] { "aaabbb", "abcd", "bdsasd", "bsdqw" };
    var data = items.GroupBy(i => i[0])
        .Select(x => new { Key = x.Key, Value = x })
        .First();
    var serializer = new JavaScriptSerializer();
    var serialized = serializer.Serialize(data);
    

    In both cases the result would be:

    {"Key":"a","Value":["aaabbb","abcd"]}
    
    0 讨论(0)
  • 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<Product>(json);
    
    0 讨论(0)
提交回复
热议问题