问题
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