How to convert c# arrays to JSON with one array item propety value set as reference to item from another

拜拜、爱过 提交于 2019-12-11 08:57:14

问题


To properly bind Java script arrays to AngularJs view I need them look like:

   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]}
    ];

Suppose I have c# arrays like:

    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]}
        };

The question is: How could I convert these C# arrays to get needed JSON arrays? I know about JSON. Net library but I didn't manage to find the solution in docs.


回答1:


Try the javascripserializer class

 var json = new JavaScriptSerializer().Serialize(drinks);
 Console.WriteLine(json);


来源:https://stackoverflow.com/questions/19953335/how-to-convert-c-sharp-arrays-to-json-with-one-array-item-propety-value-set-as-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!