【问题标题】:Newtonsoft.Json.JsonSerializationExceptionNewtonsoft.Json.JsonSerializationException
【发布时间】:2013-12-31 12:21:21
【问题描述】:

我正在尝试通过语句将 json 转换为 C# 对象

 var organizations = response.Content.ReadAsAsync<IEnumerable<Organization>>().Result;

我发现了很多问题,就像我现在面临的一样,但我没有找到正确的答案,请问我知道这个异常的原因吗

无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.IEnumerable `1[ConsoleApplication2.Organization]',因为该类型需要 JSON 数组(例如 [1 ,2,3]) 以正确反序列化。

要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为正常的 .NET 类型(例如,不是像整数这样的原始类型,而不是可以从 JSON 对象反序列化的集合类型(如数组或列表)。 JsonObjectAttribute 也可以添加到类型中,以强制它从 JSON 对象反序列化。

我正在尝试通过语句将 json 转换为 C# 对象 我发现了很多问题,就像我现在面临的一样,但我没有找到正确的答案我可以知道这个例外的原因吗 我的 Json 是

{
    "code": 0,
    "message": "success",
    "organizations": [
        {
        "organization_id": "10234695",
        "name": "Zillium Inc",
        "contact_name": "John Smith",
        "email": "johnsmith@zilliuminc.com",
        "is_default_org": false,
        "plan_type": 0,
        "tax_group_enabled": true,
        "plan_name": "TRIAL",
        "plan_period": "",
        "language_code": "en",
        "fiscal_year_start_month": 0,
        "account_created_date": "2012-02-18",
        "account_created_date_formatted": "18 Feb 2012",
        "time_zone": "Asia/Calcutta",
        "is_org_active": true,
        "currency_id": "460000000000097",
        "currency_code": "USD",
        "currency_symbol": "$",
        "currency_format": "###,##0.00",
        "price_precision": 2
        },
        {
        "organization_id": "10407630",
        "name": "Winston Longbridge",
        "contact_name": "John Smith",
        "email": "johnsmith@zilliuminc.com",
        "is_default_org": false,
        "plan_type": 0,
        "tax_group_enabled": true,
        "plan_name": "TRIAL",
        "plan_period": "",
        "language_code": "en",
        "fiscal_year_start_month": 0,
        "account_created_date": "2012-07-11",
        "account_created_date_formatted": "11 Jul 2012",
        "time_zone": "Asia/Calcutta",
        "is_org_active": true,
        "currency_id": "541000000000099",
        "currency_code": "INR",
        "currency_symbol": "Rs.",
        "currency_format": "###,##0.00",
        "price_precision": 2
        }
    ]
}

【问题讨论】:

  • 你发布的哈里:To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or chang e the deserialized type so that it is a normal .NET type (e.g. not a primitive t ype like integer, not a collection type like an array or List)

标签: c# json serialization


【解决方案1】:

您正在尝试反序列化为 IEnumerable&lt;Organization&gt;&gt; 这是一个列表,因此序列化程序需要一个 json 字符串来定义一个列表/数组,如 [{a:b}, {a:n}]

您的 json 数据似乎是一个普通的 json 对象,而不是一个数组。

这是导致异常的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    相关资源
    最近更新 更多