gpt4 book ai didi

c# - 如何将一个数组项属性值设置为对另一个项的引用的 C# 数组转换为 JSON

转载 作者:行者123 更新时间:2023-11-30 17:47:01 28 4
gpt4 key购买 nike

为了正确地将 Java 脚本数组绑定(bind)到 AngularJs View ,我需要它们看起来像:

   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 库,但我没能在文档中找到解决方案。

最佳答案

试试 javascripserializer

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

关于c# - 如何将一个数组项属性值设置为对另一个项的引用的 C# 数组转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19953335/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com