我在反序列化json响应时遇到问题。我正在使用重新装配c#库与API进行通信。响应中的RootObject.company始终为null,即使测试字段加载正确。我还尝试通过Postman检索JSON字符串,并手动对其进行反序列化,看看是否会出现问题,但它可以正常工作。我对可能出了什么问题感到困惑。同样的代码以前也适用于一系列公司,但设计发生了变化,现在只返回一家公司。请忽略登录部分,它只是用于对我的本地开发后端进行身份验证。我为我的问题创建了一个最低限度的工作示例:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var ApiIlogin = RestService.For<IMyInterface>("http://localhost:8000");
var login = ApiIlogin.Login("admin", "admin").Result;
var result = ApiIlogin.GetData(login.Token).Result;
var myString =
"{"company":{"id":1,"name":"TestComp","farms":[{"id":1,"name":"TestFarm1","cameras":[{"id":1,"name":"FakeCamera","ipAddress":"127.0.0.1","farm":1,"port":8666,"count":[],"weight":[],"area":null}],"company":1},{"id":3,"name":"TestFarm3","cameras":[],"company":1}]},"test":"Test"}";
var test = JsonSerializer.Deserialize<Rootobject>(myString);
}
}
public interface IMyInterface
{
[Get("/api/data")]
Task<Rootobject> GetData([Authorize] string token);
[Post("/api/login?username={username}&password={password}")]
Task<LoginUserResponse> Login(string username, string password);
}
public class LoginUserResponse
{
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
public int Id { get; set; }
public string Username { get; set; }
public IList<string> Roles { get; set; }
public string Token { get; set; }
public bool Authenticated { get; set; }
}
public class Rootobject
{
public Company company { get; set; }
public string test { get; set; }
}
public class Company
{
public int id { get; set; }
public string name { get; set; }
public Farm[] farms { get; set; }
}
public class Farm
{
public int id { get; set; }
public string name { get; set; }
public Camera[] cameras { get; set; }
public int company { get; set; }
}
public class Camera
{
public int id { get; set; }
public string name { get; set; }
public string ipAddress { get; set; }
public int farm { get; set; }
public int port { get; set; }
public object[] count { get; set; }
public object[] weight { get; set; }
public object area { get; set; }
}
这里是Postman检索的JSON示例,以防内联消息产生影响。
{
"company": {
"id": 1,
"name": "TestComp",
"farms": [
{
"id": 1,
"name": "TestFarm1",
"cameras": [
{
"id": 1,
"name": "FakeCamera",
"ipAddress": "127.0.0.1",
"farm": 1,
"port": 8666,
"count": [],
"weight": [],
"area": null
}
],
"company": 1
},
{
"id": 3,
"name": "TestFarm3",
"cameras": [],
"company": 1
}
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"test": "Test"
}
尽管如此,我还是发现了问题。我忘记了管理员帐户没有分配公司,所以使用该帐户登录并检索数据返回null。在Postman上,我使用了一个专门为测试而创建的用户帐户,该帐户确实分配了一家公司,所以响应如预期。我将向我的API发出警告,以防我未来的自己再次这样做。
换句话说,这是一个经典的PEBKaC。