【发布时间】:2019-07-24 18:12:49
【问题描述】:
我正在调用一个 API 端点,它返回一个 JSON 一些数据,我需要将其反序列化为可能包含 ReactiveProperty 字段的类和嵌套类(来自 UniRx 库的类型,它是 Unity3D 的 Reactive 扩展的重新实现) .
我是 C# 新手,我尝试了一些东西,但我无法按照我想要的方式实现它。
这是我的 Api 返回的 json(实际上有更多数据,但这个例子就足够了):
"user": {
"id": "87f2ae6e-af99-4f8e-9d69-08de6ad6baf8",
"username": "test",
"email": "test@test.com",
"money": 800,
"morale": 100,
"health": 100,
"credits": 15,
"energy": 100,
"banned_at": null,
"last_connection": null,
"officers": [
{
"id": "2b72d9d4-635c-4b32-9575-5df49f566e93",
"name": "David Le Salmon",
"is_available": true,
"age": 42,
"condition": 100,
"user_id": "87f2ae6e-af99-4f8e-9d69-08de6ad6baf8"
},
{
"id": "ebc4074c-7b94-4ea3-96d9-f80608972afa",
"name": "Philippe Mercier",
"is_available": true,
"age": 34,
"condition": 100,
"user_id": "87f2ae6e-af99-4f8e-9d69-08de6ad6baf8"
},
{
"id": "edba67b5-9053-4fd6-b64e-6b85f4d0cc25",
"name": "Raymond Wagner-Berthelot",
"is_available": true,
"age": 55,
"condition": 100,
"user_id": "87f2ae6e-af99-4f8e-9d69-08de6ad6baf8"
}
],
"vehicles": [
{
"id": "3161d274-ed2a-491b-8515-beb7da9bfd29",
"mileage": 0,
"health": 100,
"level": 3,
"equipment_level": 4,
"vehicle_prefab_id": "14e8d96f-0e85-40ad-b01b-5f00a37b1108"
},
{
"id": "ff984c79-4511-4ade-92d1-9bf6899a243c",
"mileage": 0,
"health": 100,
"level": 4,
"equipment_level": 4,
"vehicle_prefab_id": "14e8d96f-0e85-40ad-b01b-5f00a37b1108"
}
]
}
}
我定义了一些这样的类:
[Serializable]
public class AppState {
public User user = new User();
}
[Serializable]
public class User {
public string username;
public string email;
public ReactiveProperty<int> money = new ReactiveProperty<int>();
public ReactiveProperty<int> morale = new ReactiveProperty<int>();
public ReactiveProperty<int> health = new ReactiveProperty<int>();
public ReactiveProperty<int> energy = new ReactiveProperty<int>();
public List<Officer> officers = new List<Officer[]>();
public List<Vehicles> vehicles = new List<Vehicle>();
}
Officer和Vehicle的定义方式相同,有些字段是ReactiveProperty,有些不是。
这里是我尝试反序列化的方式:
RestClient.Get("/getAppState").Then(response => {
var stuff = JsonConvert.DeserializeObject<AppState>(response.Text);
})
此代码抛出此错误:
Could not cast or convert from System.String to UniRx.ReactiveProperty
我发现了一些“有效”的东西,我手动分配了所有 ReactiveProperty 字段,但这真的很乏味。
有没有办法在 C# 中做到这一点?
【问题讨论】:
-
欢迎来到 StackOverflow!什么是
ReactiveProperty?为什么不直接使用int? -
就像我说的,它是来自 UniRx (github.com/neuecc/UniRx) 的一个类型,它是一个用于重新实现 .NET 响应式扩展的 Unity 库。它允许我在此值更改并更新我的 UI 时收到通知。