无法将当前json对象反序列化,因为(例如。{name":" value"}})因为类型需要json数组(例如[1,2,3]) [英] Cannot deserialize the current json object because(e.g.{"name":"value"}) into type because the type requires a json array (e.g.[1, 2, 3])

查看:306
本文介绍了无法将当前json对象反序列化,因为(例如。{name":" value"}})因为类型需要json数组(例如[1,2,3])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将字符串转换为Json对象然后错误这种类型的错误显示。(

When i Convert string To Json Object Then Error This type of Error Show.(

Cannot deserialize the current json object because(e.g.{"name":"value"}) into type because the type requires a json array (e.g.[1,2,3])







Json String .... ..




Json String......

{
  "success": 1,
  "login": [
    {
      "username": "123456",
      "password": "123456",
      "store_authority": "Yes",
      "fyear": "2018-19"
    }
  ]
}





我的尝试:





What I have tried:

string Post_Status = "http://123456.com/webapi/login.php?username=" + username + "&password=" + password + "";
                WebClient webClient = new WebClient();
                webClient.Headers.Add("user-agent", "Only a test!");
                string json = webClient.DownloadString(Post_Status);
                var model = JsonConvert.DeserializeObject<List<RootObject>>(json);




public class RootObject
        {
            public string success { get; set; }
            public List<Login> login { get; set; }
        }




public class Login
        {
            public string username { get; set; }
            public string password { get; set; }		
            public string store_authority { get; set; }		
            public string fyear { get; set; }		
        }

推荐答案

以下Json

The following Json
{
  "success": 1,
  "login": [
    {
      "username": "123456",
      "password": "123456",
      "store_authority": "Yes",
      "fyear": "2018-19"
    }
  ]
}



不是一个可枚举的Root Objects。它包含一个列表但不是一个。



反序列化的正确方法是:


Is not an enumerable of "Root Objects. It contains a list but isn't one.

The correct way to deserialize it is:

var model = JsonConvert.DeserializeObject<RootObject>(json);





要成为desrializer的有效JSON,它必须如下所示:



To be valid JSON for your desrializer it would have to look like this:

[{
  "success": 1,
  "login": [
    {
      "username": "123456",
      "password": "123456",
      "store_authority": "Yes",
      "fyear": "2018-19"
    }
  ]
}]



注意额外的方括号



希望有帮助

Andy


Note the extra square brackets

Hope that helps
Andy


JsonConvert.DeserializeObject<List<RootObject>>(json);





您将json反序列化为RootObject对象数组,但是json不包含这些项的数组,只有一个,因此反序列化为RootObject,您不需要List。



You are deserialising the json into an array of RootObject objects, however the json don't contain an array of those items, only one, so deserialise to just RootObject, you don't need the List.


这篇关于无法将当前json对象反序列化,因为(例如。{name&quot;:&quot; value&quot;}})因为类型需要json数组(例如[1,2,3])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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