简体   繁体   English

如何创建JObject的JArray?

[英]How to create JArray of JObject?

I'm trying to fill the object details with an array of JObject . 我试图用JObject数组填充对象details The informations are available in the contactAddresses which is a AddressModel[] . 该信息可在contactAddresses中获得,后者是一个AddressModel[]

Whith the following code, I get the following error: 如果执行以下代码,则会出现以下错误:

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));

What am I doing wrong ? 我究竟做错了什么 ?

You are missing the closing quotes around each data field, as well as the comma between them. 您会丢失每个数据字段周围的右引号以及它们之间的逗号。 You need something like; 您需要类似的东西;

addresses.Add(JObject.Parse(
            @"{""street"":""" + address.Street + "\", " +
            @"""city"":""" + address.City + "\", " + 
            @"""postalCode"":""" + address.PostalCode + 
        @"""}"));

Seems like your ultimate goal is to end up with some JSON that represents a list of addresses. 似乎您的最终目标是最终得到一些表示地址列表的JSON。 I know you mentioned JObject and JArray, but you thought that implementation was ugly. 我知道您提到了JObject和JArray,但是您认为实现很丑。 Here's an alternative. 这是另一种选择。

string json = JsonConvert.SerializeObject(contactAddresses);

The resulting json should look like this (once formatted): 生成的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"},
]

You can apply attributes to properties of the AddressModel class if you want the output to appear differently 如果希望输出以不同的方式出现,可以将属性应用于AddressModel类的属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM