我有一个对象,当使用JsonConvert.SerializeObject
方法转换为JSON字符串时,它看起来如下:
{"01":{"CompanyName":"Hertz","Cars":"Ford, BMW, Fiat"},
"02":{"CompanyName":"Avis","Cars":"Dodge, Nash, Buick"}}
如何使用Formatting
参数使结果看起来像这样:
{"01":{"CompanyName":"Hertz","Cars":["Ford", "BMW", "Fiat"]},
"02":{"CompanyName":"Avis","Cars":["Dodge", "Nash", "Buick"]}}
正如注释中提到的@dbc,您不能使用JsonConvert.SerializeObject
的Formatting
参数来影响JSON中的特定值是否被方括号包围。Formatting
参数仅控制Json.Net是否会在Json输出中添加缩进和换行,以使人类更容易阅读。
在JSON中,方括号用于表示值的数组,而不是单个值。因此,如果您想为特定属性添加方括号,最简单的方法是更改该属性在类中的声明方式,使其相应地表示数组(或列表)。
基于您最初的JSON,我假设您有一个类,它看起来像这样:
public class Company
{
public string CompanyName { get; set; }
public string Cars { get; set; }
}
您正在创建类似于以下内容的JSON:
var results = new Dictionary<string, Company>();
results.Add("01", new Company
{
CompanyName = "Hertz",
Cars = "Ford, BMW, Fiat"
});
results.Add("02", new Company
{
CompanyName = "Avis",
Cars = "Dodge, Nash, Buick"
});
string json = JsonConvert.SerializeObject(results);
要在JSON中获得方括号,请将Cars
属性的类型从string
更改为List<string>
:
public class Company
{
public string CompanyName { get; set; }
public List<string> Cars { get; set; }
}
当然,您还需要对填充结果的代码进行相应的更改:
var results = new Dictionary<string, Company>();
results.Add("01", new Company
{
CompanyName = "Hertz",
Cars = new List<string> { "Ford", "BMW", "Fiat" }
});
results.Add("02", new Company
{
CompanyName = "Avis",
Cars = new List<string> { "Dodge", "Nash", "Buick" }
});
string json = JsonConvert.SerializeObject(results);
下面是一个简短的演示:https://dotnetfiddle.net/lgg9jk