1

要将 Java 脚本数组正确绑定到 AngularJs 视图,我需要它们如下所示:

   var ingridients = [
       {name: 'Vodka'},
       {name: 'Gin'},
       {name: 'Rum'}
    ];

    var drinks = [
       {name: 'Bloody Mary', basicIngridient: ingridients[0]},
       {name: 'Gin & Tonic', basicIngridient: ingridients[1]},
       {name: 'Daiquiry', basicIngridient: ingridients[2]}
    ];

假设我有 c# 数组,例如:

    class Drink
        {
            public string Name { get; set; }
            public Ingridient BasicIngridient { get; set; }
        }

    class Ingridient
        {
            public string Name { get; set; }
        }

    static Ingridient[] ingridients = new Ingridient[] 
        { 
            new Ingridient { Name = "Vodka" },
            new Ingridient { Name = "Gin" },
            new Ingridient { Name = "Rum"}
        };

    Drink[] drinks = new Drink[]
        {
            new Drink{ Name = "Bloody Mary", BasicIngridient = ingridients[0]},
            new Drink{ Name = "Gin & Tonic", BasicIngridient = ingridients[1]},
            new Drink{ Name = "Daiquiri", BasicIngridient = ingridients[2]}
        };

问题是:如何转换这些 C# 数组以获得所需的 JSON 数组?我知道 JSON。Net 库,但我没有设法在文档中找到解决方案。

4

1 回答 1

2

尝试javascripserializer

 var json = new JavaScriptSerializer().Serialize(drinks);
 Console.WriteLine(json);
于 2013-11-13T12:13:17.513 回答