将json数据反序列化为ienumerable时出错 [英] Error with deserializing json data into ienumerable

查看:104
本文介绍了将json数据反序列化为ienumerable时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我得到的例外情况如下:



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了解我的json正在返回单个数据,我试图通过IEnumerable接口反序列化,所以我可以遍历它的列表。



我的json数据:





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":""
}





我尝试过:



我的json课程:





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





我不能了解如何使用Ienumerator迭代集合。任何帮助或想法将不胜感激。



I am not able understand how to iterate over a collection using Ienumerator. Any help or idea will be appreciated.

推荐答案

您的数据有一个名为result的属性,这是一个数组,所以你需要一个反映它的类。类似



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


您可以使用 quicktype 从您的JSON数据生成代码。



You can use sites like quicktype to generate your code from your JSON data.

// <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();
    }
}


这篇关于将json数据反序列化为ienumerable时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆