C# 无法反序列化当前的 JSON 对象(例如 {"name":"value"})

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29896264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:21:37  来源:igfitidea点击:

Cannot deserialize the current JSON object (e.g. {"name":"value"})

c#jsonjson.net

提问by Samir Rawat

This is my JSON data

这是我的 JSON 数据

{
    "logInResult": [
        {
            "Name": "yogesh singh",
            "cityName": "",
            "img": "DefaultImage/D_Vp_Men.png",
            "usrId": "374"
        }
    ]
}

and this is my code

这是我的代码

public async Task<ActionResult> Index()
{

    HttpClient webClient1 = new HttpClient();
    Uri uri = new Uri("http://m.vinipost.com/service/userprofile.svc/[email protected]&pass=12345");

    HttpResponseMessage response1;

    response1 = await webClient1.GetAsync(uri);

    var jsonString = await response1.Content.ReadAsStringAsync();

    var _Data = JsonConvert.DeserializeObject<List<JClass>>(jsonString);
    foreach (JClass Student in _Data)
    {
        ViewBag.Message += Student.Name + ", ";
    }
    dynamic obj = JsonConvert.DeserializeObject(jsonString);
    ViewBag.Message += obj.data.Name;

    return View();
}

and the error is

错误是

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MvcSumit1.Models.JClass]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To 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) 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. Path 'logInResult', line 1, position 15.

无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[MvcSumit1.Models.JClass]”,因为该类型需要一个 JSON 数组(例如 [1, 2,3]) 以正确反序列化。要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型)可以从 JSON 对象反序列化的数组或列表)。JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。路径“logInResult”,第 1 行,位置 15。

回答by Hyman Miller

Your question seems to be a duplicate of: Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

您的问题似乎与以下内容重复:Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class



You are trying to deserialize your JSON objectinto an JSON array.

您正在尝试将 JSON对象反序列化为 JSON数组

Store just the content of logInResultinto jsonString, that is:

只存储logInResultinto的内容jsonString,即:

[{"Name":"yogesh singh","cityName":"","img":"DefaultImage\/D_Vp_Men.png","usrId":"374"}]

[{"Name":"yogesh singh","cityName":"","img":"DefaultImage\/D_Vp_Men.png","usrId":"374"}]

This of course assumes that you got your JClasscorrect in the first place.

这当然假设您首先得到了JClass正确的答案。

回答by typie34

You should create the following classes in order to map your json data to actual classes.

您应该创建以下类,以便将 json 数据映射到实际类。

    public class LogInResult
{
    public string Name { get; set; }
    public string cityName { get; set; }
    public string img { get; set; }
    public string usrId { get; set; }
}

public class RootObject
{
    public List<LogInResult> logInResult { get; set; }
}

You can then store the RootObject for further processing:

然后,您可以存储 RootObject 以供进一步处理:

var result = JsonConvert.DeserializeObject<RootObject>(jsonString);

By using the getter for the list, you can get the list and iterate it as usual.

通过对列表使用 getter,您可以像往常一样获取列表并对其进行迭代。

回答by garryp

You're C# code thinks it is reading this:

你是 C# 代码认为它正在阅读:

[
    {
        "Name": "yogesh singh",
        "cityName": "",
        "img": "DefaultImage/D_Vp_Men.png",
        "usrId": "374"
    }
]

i.e. an array of objects, when in fact it is reading an object with a property logInResult, which is an array.

即一个对象数组,实际上它正在读取一个具有属性 logInResult 的对象,它是一个数组。

回答by Krunal Mevada

You can't directly deserialize from your API response using JsonConvert.DeserializeObject.

你不能直接从你的 API 响应中反序列化使用 JsonConvert.DeserializeObject.

Try this below code :

试试下面的代码:

JObject jsonResponse = JObject.Parse(jsonString);
JObject objResponse = (JObject)jsonResponse["logInResult"];
Dictionary<string, JArray> _Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, JArray>>(objResponse.ToString());

Hope this will help you.

希望这会帮助你。

回答by Saurabh Chauhan

I have faced the same issue, just wanted to point out when there is an array or list exist in JSON like in logInResults is a list of a type, so while deserializing JSON convert is not able to understand that, so what you can do it create your model in this way.

我遇到了同样的问题,只是想指出当 JSON 中存在一个数组或列表时,例如 logInResults 是一个类型的列表,所以虽然反序列化 JSON 转换无法理解,所以你可以做什么以这种方式创建您的模型。

Class  giveName
{
  givenName[] logInResult {get;set;}         // can use list also will work fine
}

public class giveName2
{
   public string Name {get;set;}
   public string cityName {get;set;}
   public string img {get;set;}
   public string usrId {get;set;}
}

i will tell you why because see the first curly braces of your json object for that to work, you must have created a type(class) which has a property named logInResult, in the same way object of which the list is made up has to be provided a type and then the properties matching with list items

我会告诉你为什么,因为看到你的 json 对象的第一个花括号才能工作,你必须创建一个类型(类),它有一个名为 logInResult 的属性,就像组成列表的对象一样提供一个类型,然后提供与列表项匹配的属性

Note: giveName and giveName2 is the name you can give yourself it wont matter with class name

注意:giveName 和 giveName2 是你可以给自己起的名字,与类名无关