Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
Hello folks,

The exception I'm getting is as follows:

"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.IEnumerable`1 because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'result', line 2, position 12.


i understood that my json is returning single data and i am trying to deserialize over IEnumerable interface so I can loop through its list.

My json data:

{
"result":[
{"Alert Message":" unreachable[Down]",
"Event Time":"2019-04-01 18:47:18",
"Threshold Value":"Down",
"Source Type":"ROUTER",
"Severity":"Unreachable",
"Metric Name":"Status",
"Source Host":"1.1.1.1"
}],
"success":"true",
"message":""
}


What I have tried:

My json class:

class JsonData
    {
        [JsonProperty("Alert Message")]
        public string AlertMessage { get; set; }

        [JsonProperty("Event Time")]
        public DateTime EventTime { get; set; }


        [JsonProperty("Threshold Value")]
        public string ThresholdValue { get; set; }

        [JsonProperty("Source Type")]
        public string SourceType { get; set; }

        [JsonProperty("Severity")]
        public string Severity { get; set; }

        [JsonProperty("Metric Name")]
        public string MetricName { get; set; }

        [JsonProperty("Source Host")]
        public string SourceHost { get; set; }
    }



My code to deserialize:

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

class ApiDemo
    {

string filepath = @"c:\jsonData.json";
            
                using (StreamReader r = new StreamReader(filepath))
                {
                    var json = r.ReadToEnd();
                    var jobj = JObject.Parse(json);
                    string  res = jobj.ToString();
IEnumerable<result> deserializedlistobj = (IEnumerable<result>)JsonConvert.DeserializeObject(res, typeof(IEnumerable<result>));


I am not able understand how to iterate over a collection using Ienumerator. Any help or idea will be appreciated.
Posted
Updated 24-Apr-19 22:40pm
v3
Comments
Richard MacCutchan 22-Apr-19 6:23am    
As the message states, the data you are trying to deserialize is not a recognised array. Also, where is the definition of the "result" type.

Your data has a property called "result" which is an array so you need a class that reflects that. Something like

class MyData
    {
        [JsonProperty("result")]
        public List<JsonData> Result { get; set; }

        [JsonProperty("success")]
        public bool Success { get; set; }

        [JsonProperty("message")]
        public string Message { get; set; }
}


then deserialise to that

MyData deserializedlistobj = (MyData)JsonConvert.DeserializeObject(res, typeof(MyData));
 
Share this answer
 
Comments
Member 14202729 23-Apr-19 1:20am    
Thank you @fes-sitecore. I am able to deserialize json into custom class collection called jsonData.But i am not sure how i will get the specified data like "EventTime" from json data. how do i use linq query to get the specified field from json data.
F-ES Sitecore 23-Apr-19 15:00pm    
Something like

List<DateTime> eventTimes = deserializedlistobj.Result.Select(r => r.EventTime).ToList();
You can use sites like quicktype to generate your code from your JSON data.

C#
// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using QuickType;
//
//    var welcome = Welcome.FromJson(jsonString);

namespace QuickType
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Welcome
    {
        [JsonProperty("result")]
        public Result[] Result { get; set; }

        [JsonProperty("success")]
        [JsonConverter(typeof(ParseStringConverter))]
        public bool Success { get; set; }

        [JsonProperty("message")]
        public string Message { get; set; }
    }

    public partial class Result
    {
        [JsonProperty("Alert Message")]
        public string AlertMessage { get; set; }

        [JsonProperty("Event Time")]
        public DateTimeOffset EventTime { get; set; }

        [JsonProperty("Threshold Value")]
        public string ThresholdValue { get; set; }

        [JsonProperty("Source Type")]
        public string SourceType { get; set; }

        [JsonProperty("Severity")]
        public string Severity { get; set; }

        [JsonProperty("Metric Name")]
        public string MetricName { get; set; }

        [JsonProperty("Source Host")]
        public string SourceHost { get; set; }
    }

    public partial class Welcome
    {
        public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, QuickType.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }

    internal class ParseStringConverter : JsonConverter
    {
        public override bool CanConvert(Type t) => t == typeof(bool) || t == typeof(bool?);

        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return null;
            var value = serializer.Deserialize<string>(reader);
            bool b;
            if (Boolean.TryParse(value, out b))
            {
                return b;
            }
            throw new Exception("Cannot unmarshal type bool");
        }

        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
        {
            if (untypedValue == null)
            {
                serializer.Serialize(writer, null);
                return;
            }
            var value = (bool)untypedValue;
            var boolString = value ? "true" : "false";
            serializer.Serialize(writer, boolString);
            return;
        }

        public static readonly ParseStringConverter Singleton = new ParseStringConverter();
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900