c# - 将 JSON 反序列化为具有 ReactiveProperty 字段的嵌套类
问题描述
我正在调用一个 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# 中做到这一点?
解决方案
使 Reactive 属性字段为 NonSerializable。
制作新的可序列化字符串字段。
反序列化 JSON。
向您的类添加一些函数,将字符串表示形式转换为您的 ReactiveProperty 变量。
在反序列化 JSON 后调用这些函数。
注意:我不熟悉 ReactiveProperty,您需要调查该库以找到将字符串转换为这些对象的最佳方法。
推荐阅读
- jhipster - 向实体添加新属性后,Jhipster 与所有实体发生冲突
- java - JAVA:java.nio.Files move 命令不适用于共享 NAS 位置
- python - 提取相同标签的信息
- javascript - 使用 css-grid 和 flexbox 时如何排列元素?
- python - 3D Ursina 游戏中的照明
- python - 转换嵌套列表类型
- python - sqlite3.OperationalError:我的代码输入不完整
- reactjs - 在 React 中从 API 获取加载器状态
- pointers - glibc malloc 什么时候省略块链表指针
- android - 处理 RX 中的 response.body == null