无法将当前JSON对象(例如{“ name”:“ value”})反序列化为type

时间:2019-09-11 18:45:45

标签: c# list deserialization json-deserialization

我的请求如下所示:

{
  "count": 5,
  "pages": 1,
  "result": [
    {
      "id": "00000000-0000-0000-0000-000000000001",
      "orgId": "00000000-0000-0000-0000-000000000111",
      "userName": "SamPowell",
      "firstName": "Sam",
      "lastName": "Powell",
      "password": "tytrtyrty",
      "token": null,
      "badge": "001",
      "defaultLanguage": "english",
      "supervisorId": "00000000-0000-0000-0000-000000000000",
      "inactive": false,
}]
}

反序列化失败

_users = JsonConvert.DeserializeObject<List<ApplicationUser>>_restResponse.Content);

Application User类缺少“计数”和“页面”

如何将其添加到列表中

我需要根据对象结果Assert.IsNotNull(_users[0].userName.Equals("SamPowell"));

进行如下声明

2 个答案:

答案 0 :(得分:3)

您的响应显示的是分页结果,因此您的模型需要看起来像这样:

public class PagedResult<T>
{
    public int count { get; set; }
    public int pages { get; set; }
    public T[] result { get; set; }
}

public class ApplicationUser
{
    public string id { get; set; }
    public string orgId { get; set; }
    public string userName { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string password { get; set; }
    public object token { get; set; }
    public string badge { get; set; }
    public string defaultLanguage { get; set; }
    public string supervisorId { get; set; }
    public bool inactive { get; set; }
}

然后您将反序列化并对其进行测试,如下所示:

public class Testing
{
    [Test]
    public void Deserialize()
    {
        var page = JsonConvert.DeserializeObject<PagedResult<ApplicationUser>>(json);
        var users = page.result;
        Assert.IsNotNull(users[0].userName.Equals("SamPowell"));
    }    

     private string json = @""; //your json
}

答案 1 :(得分:0)

您明确地告诉它要反序列化到ApplicationUser对象类型的列表。显然,您也承认对象ApplicationUser具有与json字符串不同的属性:

“应用程序用户类缺少“计数”和“页面”,如何将其添加到列表中”

_users = JsonConvert.DeserializeObject> _restResponse.Content);

您要么

创建一个包含属性和“应用程序用户”列表的新类

(可能是我所看到的,这是您编写自动化测试的最可能路径,因此您可能没有扮演mod类的角色),您需要像这样使用Newtonsoft动态对象进行解析:

import pygame

pygame.init()

work = True
b_y = 425
key = pygame.key.get_pressed()
newWindow = pygame.display.set_mode((500, 500))
pygame.display.set_caption("NewFile")

class player:

    def __init__(self, vel, x):
        self.x = x
        self.vel = vel

    def playerdraw(self):
        pygame.draw.rect(newWindow, (255, 255, 255),  (p1.x, 425,
40,20))

    def  move(self):
        key = pygame.key.get_pressed() # You need to read the get_pressed key function on each loop
        if key[pygame.K_LEFT] and p1.x>5:
             p1.x -=  self.vel
        elif key[pygame.K_RIGHT] and p1.x < 455:
             p1.x += self.vel  


p1 = player(2, 250)
b_x = p1.x

while work:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            work= False

    newWindow.fill((0, 0, 0))

    p1.move()
    p1.playerdraw()

    pygame.display.update()


pygame.quit()