简体   繁体   中英

Iterating a JSON object array name value pair in c#

I've taken this example from a similar question here:

Iterating over a JSON object (NOT an array) in C#

But my data format is a little different, it has array brackets.

As pointed out I can have an undefined number of entries, I want to walk through the entries and extract the data structure into an array/list of objects based on the class defined.

{
  "-KeArK3V02mXYWx2OMWh" : [{
    "Description" : "this is a description",
    "Location" : "Atlanta",
    "Name" : "Event One",
    "Time" : "2017-03-01T21:53:12.924645Z"
  }],
  "-KeAtCNF_rmewZ_U3PpH" : [{
    "Description" : "another description",
    "Location" : "Charlotte",
    "Name" : "Event Two",
    "Time" : "2017-03-01T22:01:25.603547Z"
  }],
  "-KeAtd8CQW_EfH3Sw4YQ" : [{
    "Description" : "description goes here",
    "Location" : "Toronto",
    "Name" : "Event Three",
    "Time" : "2017-03-01T22:03:19.3953859Z"
  }]
}

and I have a class called Event that is defined as follows

class Title {
  public string Description { get; set; }
  public string Location { get; set; }
  public string Name { get; set; }
  public DateTime Time { get; set; }
}

The answer given there (which I thought was correct) isn't working

Dictionary<string, Title> elist = JsonConvert.DeserializeObject<Dictionary<string, Title>>(jsonString);

It gives me an error:

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'Title' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '-KeArK3V02mXYWx2OMWh', line 2, position XX.

There is a problem with structure of Json. Your json has format like Key and value but value is array as per json format. You have to do following thing.

Dictionary<string,Title[]> elist = JsonConvert.DeserializeObject<Dictionary<string, Title[]>>(jsonString);

Above solution is simplest one.

Second solution. ( You have to modify as your need but current json will work)

 public class TitleConverter : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JArray jObject = JArray.Load(reader);

            Title title = JsonConvert.DeserializeObject<Title>(jObject[0].ToString());
                return title;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            if (objectType.Name == "Title")
                return true;
            return false;
        }
    }

Now use like this.

Dictionary<string,Title> elist = JsonConvert.DeserializeObject<Dictionary<string, Title>>(jsonString,new TitleConverter());

Unless I am missing something, you linked a question titled "Iterating over a JSON object (NOT an array) in C#"

However your JSON clearly contains an array, you even notice that yourself:

"But my data format is a little different, it has array brackets."

So you simply need to change you Title to an array of Title ( Title[] ):

Dictionary<string, Title[]> elist = JsonConvert.DeserializeObject<Dictionary<string, Title[]>>(jsonString);

If you look at your json you can clearly see its defined as an array of objects (look at the '[' and ']'):

"-KeAtd8CQW_EfH3Sw4YQ" : [{
    "Description" : "description goes here",
    "Location" : "Toronto",
    "Name" : "Event Three",
    "Time" : "2017-03-01T22:03:19.3953859Z"
}]

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