C# 无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17762032/
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-10 10:25:37  来源:igfitidea点击:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

c#asp.netjson

提问by sakir

I have a class like this;

我有一堂这样的课;

public  class MyStok
{
    public int STId { get; set; }
    public int SM { get; set; }
    public string CA { get; set; }
    public string Br { get; set; }
    public string BNo { get; set; }
    public decimal Vat { get; set; }
    public decimal Price { get; set; }
}

I deserilaze like this;

我像这样反序列化;

string sc=  e.ExtraParams["sc"].ToString();
MyStok myobj = JSON.Deserialize<MyStok>(sc);

my output seems to like this ( string sc) on fiddler

我的输出似乎像 fiddler 上的这个(字符串 sc)

[
    {
        "STId": 2,
        "CA": "hbh",
        "Br": "jhnj",
        "SM": 20,
        "Vat": 10,
        "Price": 566,
        "BNo": "1545545"
    }
]

but I get the error Cannot deserialize the current JSON array (e.g. [1,2,3]) into type whats wrong in those codes.

但我收到错误无法将当前 JSON 数组(例如 [1,2,3])反序列化为这些代码中的错误类型。

thank you .

谢谢你 。

采纳答案by dasblinkenlight

It looks like the string contains an array with a single MyStokobject in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

看起来该字符串包含一个数组,其中包含一个MyStok对象。如果从输入的两端删除方括号,您应该能够将数据反序列化为单个对象:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStokobjects, and take the object at index zero.

您还可以将数组反序列化为MyStok对象列表,并在索引为零处获取对象。

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

回答by Janty

For array type Please try this one.

对于数组类型请尝试这个。

 List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));

Please See here for details to deserialise Json

参阅此处了解反序列化 Json 的详细信息

回答by Aditi_Systematix

HttpClient webClient = new HttpClient();
Uri uri = new Uri("your url");
HttpResponseMessage response = await webClient.GetAsync(uri)
var jsonString = await response.Content.ReadAsStringAsync();
var objData = JsonConvert.DeserializeObject<List<CategoryModel>>(jsonString);