简体   繁体   中英

JSON Array in Newtonsoft using C#

I am pretty new to using JSON and Newtonsoft together and I am trying to replicate this format without success using JArray(). Does anyone have any ideas on how this can be accomplished?

   "attrList":[
      {
         "name":"Attendee Status",
         "val":"Accepted"
      },
      {
         "name":"Attendee Type",
         "val":"Attendee"
      }
   ]

Using manual JArray creation, you can do it as follows:

var root = new JObject
(
    new JProperty("attrList",
        new JArray
        (
            new JObject
            (
                new JProperty("name", "Attendee Status"),
                new JProperty("val", "Accepted")
            ),                  
            new JObject
            (
                new JProperty("name", "Attendee Type"),
                new JProperty("val", "Attendee")
            )
        )
    )
);

You wrote The error I keep running into is the keys being the same , so you are probably doing something like this instead:

var root = new JObject
(
    new JProperty("attrList",
        new JArray
        (
            new JObject
            (
                new JProperty("name", "Attendee Status"),
                new JProperty("val", "Accepted"),
                new JProperty("name", "Attendee Type"),
                new JProperty("val", "Attendee")
            )
        )
    )
);

Notice that only one inner object is being created rather than two? If you forget to allocate both objects you will end up trying to add the properties "name" and "val" twice, thereby reproducing the problem.

Sample fiddle .

See also Creating JSON: Manually Creating JSON .

public class Parent
{
    public List<Attribute> attrList{ get; set; }
}

public class Attribute
{
    public string name{ get; set; }
    public string val{ get; set; }
}

var parsedParent = JsonConvert.DeserializeObject<Parent>(
   "{ 'attrList':[ { 'name':'Attendee Status', 'val':'Accepted' }, { 'name':'Attendee Type', 'val':'Attendee' } ] }"
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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