本文介绍了JsonConvert.Deserialize无法识别数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此有些困惑.我所做的所有检查都表明它是有效的Json数组,但JsonConvert.Deserialize则说它是一个对象.有人可以指出我做错了什么吗?

I'm a little stumped on this one. Everything I do to check this out says it is a valid Json array, but JsonConvert.Deserialize says it is an object. Can someone point out what I'm doing wrong?

要复制的代码:

var data = "[{\"User\": {\"Identifier\": \"24233\",\"DisplayName\": \"Commerce Test Student\",\"EmailAddress\": \"[email protected]\",\"OrgDefinedId\": \"UniqueId1\",\"ProfileBadgeUrl\": null,\"ProfileIdentifier\": \"zzz123\"},\"Role\": {\"Id\": 153,\"Code\": null,\"Name\": \"Commerce Student\"}}]";

var items = JsonConvert.DeserializeObject<List<T>>(data);

其中T是与以下格式匹配的对象:

Where T is an object that matches the format below:

public class OrgUnitUser
{
    public User User { get; set; }
    public RoleInfo Role { get; set; }
}

public class User
{
    public string Identifier { get; set; }
    public string DisplayName { get; set; }
    public string EmailAddress { get; set; }
    public string OrgDefinedId { get; set; }
    public string ProfileBadgeUrl { get; set; }
    public string ProfileIdentifier { get; set; }
}
public class RoleInfo
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

这会导致错误

Newtonsoft.Json.JsonSerializationException:无法将当前JSON对象(例如{"name":"value"})反序列化为类型'System.Collections.Generic.List`1 [CoverPages.Models.D2L.OrgUnitUser]',因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化.

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[CoverPages.Models.D2L.OrgUnitUser]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

任何/所有帮助都将受到赞赏!

Any/all help is appreciated!

推荐答案

var data = "[{\"User\": {\"Identifier\": \"24233\",\"DisplayName\": \"Commerce Test Student\",\"EmailAddress\": \"[email protected]\",\"OrgDefinedId\": \"UniqueId1\",\"ProfileBadgeUrl\": null,\"ProfileIdentifier\": \"zzz123\"},\"Role\": {\"Id\": 153,\"Code\": null,\"Name\": \"Commerce Student\"}}]";

public class User
{
    public string Identifier { get; set; }
    public string DisplayName { get; set; }
    public string EmailAddress { get; set; }
    public string OrgDefinedId { get; set; }
    public object ProfileBadgeUrl { get; set; }
    public string ProfileIdentifier { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public object Code { get; set; }
    public string Name { get; set; }
}

public class RootObject
{
    public User User { get; set; }
    public Role Role { get; set; }
}

var items = JsonConvert.DeserializeObject<List<RootObject>>(data);

var items = JsonConvert.DeserializeObject<List<RootObject>>(data)[0];

尝试此代码,我认为他工作得很好

Try this code I thinks he working good

结果:

这篇关于JsonConvert.Deserialize无法识别数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:38