如何创建JObject的JArray?

时间:2015-10-28 13:17:11

标签: c# asp.net json.net

我尝试使用details数组填充对象JObjectcontactAddresses中提供的信息为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));

我做错了什么?

2 个答案:

答案 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类的属性