我尝试使用details
数组填充对象JObject
。 contactAddresses
中提供的信息为AddressModel[]
。
使用以下代码,我收到以下错误:
Newtonsoft.Json.JsonReaderException : After parsing a value an unexpected character was encountered
JArray addresses = new JArray();
foreach (AddressModel address in contactAddresses)
{
addresses.Add(JObject.Parse(
@"{""street"":""" + address.Street +
@"""city"":""" + address.City +
@"""postalCode"":""" + address.PostalCode +
@"""}"));
}
details.Add(new JProperty("addresses", addresses));
我做错了什么?
答案 0 :(得分:2)
您缺少每个数据字段周围的结束引号,以及它们之间的逗号。你需要类似的东西;
addresses.Add(JObject.Parse(
@"{""street"":""" + address.Street + "\", " +
@"""city"":""" + address.City + "\", " +
@"""postalCode"":""" + address.PostalCode +
@"""}"));
答案 1 :(得分:0)
似乎你的最终目标是最终得到一些代表地址列表的JSON。我知道你提到过JObject和JArray,但你认为实现很丑陋。这是另一种选择。
string json = JsonConvert.SerializeObject(contactAddresses);
生成的json
应该如下所示(格式化后):
[
{"Street": "123 Mockingbird Lane", "City": "New York City", "PostalCode": "11111"},
{"Street": "1600 Penn Ave", "City": "Washington DC", "PostalCode": "22222"},
{"Street": "2400 University Dr", "City": "Fort Worth", "PostalCode": "33333"},
]
如果希望输出显示不同
,则可以将属性应用于AddressModel
类的属性