【发布时间】:2019-06-05 08:46:03
【问题描述】:
我有以下HAL+JSON 示例:
{
"id": "4a17d6fe-a617-4cf8-a850-0fb6bc8576fd",
"country": "DE",
"_embedded": {
"company": {
"name": "Apple",
"industrySector": "IT",
"owner": "Klaus Kleber",
"_embedded": {
"emailAddresses": [
{
"id": "4a17d6fe-a617-4cf8-a850-0fb6bc8576fd",
"value": "test2@consoto.com",
"type": "Business",
"_links": {
"self": {
"href": "https://any-host.com/api/v1/customers/1234"
}
}
}
],
"phoneNumbers": [
{
"id": "4a17d6fe-a617-4cf8-a850-0fb6bc8576fd",
"value": "01670000000",
"type": "Business",
"_links": {
"self": {
"href": "https://any-host.com/api/v1/customers/1234"
}
}
}
],
},
"_links": {
"self": {
"href": "https://any-host.com/api/v1/customers/1234"
},
"phoneNumbers": {
"href": "https://any-host.com/api/v1/customers/1234"
},
"addresses": {
"href": "https://any-host.com/api/v1/customers/1234"
},
}
},
},
"_links": {
"self": {
"href": "https://any-host.com/api/v1/customers/1234"
},
"legalPerson": {
"href": "https://any-host.com/api/v1/customers/1234"
},
"naturalPerson": {
"href": "https://any-host.com/api/v1/customers/1234"
}
}
}
以及以下型号:
public class Customer
{
public Guid Id { get; set; }
public string Country { get; set; }
public LegalPerson Company { get; set; }
}
public class LegalPerson
{
public string Name { get; set; }
public string IndustrySector { get; set; }
public string Owner { get; set; }
public ContactInfo[] EmailAddresses { get; set; }
public ContactInfo[] PhoneNumbers { get; set; }
}
public class ContactInfo
{
public Guid Id { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
现在,由于_embbeded,我无法使用Newtonsoft.Json 进行开箱即用的序列化,因为那时Company 将是null;
我希望看到 Json.NET 的 native hal+json support,但它只有一个建议使用自定义 JsonConverter。
我开始自己创建一个自定义的,但对我来说感觉就像“重新发明轮子”。
那么,有谁知道解决这个问题的聪明方法?
更新:
- 重要的是不要更改模型/类。我可以添加属性,但不能更改它的结构。
【问题讨论】:
-
你看过 hal 序列化:npmjs.com/package/hal-serializer 吗?
-
@AhmedBinGamal 我会做,但这是一个节点解决方案,我正在寻找一个 c# 永久解决方案。
-
你说你不能改变你的模型,扩展或覆盖它们怎么样?
-
这将是一个问题。我这里的场景是,在生产系统上完全工作,并且数据模式的源更改为 hal+json 响应。我不能去更改模型的结构或扩展/覆盖模型 - 否则,我将需要触及整个系统。我需要一个精确的方法。添加一些属性——我可以在运行时做——或者添加
JsonConverter,或者其他我没有想到的选项。 -
也许只是使用手动 LINQ to JSON -> 对象版本而不进行任何反序列化?它可能比编写反序列化器更容易
标签: c# json json.net deserialization json-deserialization