【问题标题】:Parsing a nested and complex JSON response in C#在 C# 中解析嵌套的复杂 JSON 响应
【发布时间】:2017-05-21 05:59:55
【问题描述】:

解析复杂 JSON 对象的最佳做法是什么,在这种情况下被发布到控制器操作?

预先创建一个模型类很脆弱,因为发送者会随着时间的推移改变 JSON 的结构。

控制器

        // POST api/values
        public void Post([FromBody] AdminNotesModel value)
        {

           // do something with JSON...
        }

有效负载示例

    {
"type": "notification_event",
"app_id": "cl00zu9g",
"data": {
"type": "notification_event_data",
"item": {
"type": "conversation",
"id": "7594189485",
"created_at": 1483576126,
"updated_at": 1483650387,
"user": {
"type": "user",
"id": "586d933eb76086661e49c991",
"user_id": "83c3224b-45b2-4f7d-a978-40c836564658",
"name": "Byrne MichaelaS",
"email": "michaela.byrne@yellowjackets.bhsu.edu"
},
"assignee": {
"type": "admin",
"id": "848395",
"name": "Linda",
"email": "linda@aol.com"
},
"conversation_message": {
"type": "conversation_message",
"id": "69270153",
"subject": "<p>Summer internship possibilities </p>",
"body": "<p>Hello,</p><p>My name is Joe Foo. </p><p>Thanks for your time and please let me know if this might be a possibility.</p>",
"author": {
"type": "user",
"id": "586d933eb76086661e49c991"
},
"attachments": []
},
"conversation_parts": {
"type": "conversation_part.list",
"conversation_parts": [
{
"type": "conversation_part",
"id": "416288171",
"part_type": "note",
"body": "<p>Sent to Vicki</p>",
"created_at": 1483650387,
"updated_at": 1483650387,
"notified_at": 0,
"assigned_to": null,
"author": {
"type": "admin",
"id": "848395",
"name": "Linda"
},
"attachments": [],
"external_id": null
}
],
"total_count": 1
},
"open": true,
"read": true,
"metadata": {},
"tags": {
"type": "tag.list",
"tags": []
},
"links": {
"conversation_web": "https://app.intercom.io/a/apps/"
}
}
},
"links": {},
"id": "notif_d2e41790-d38a-11e6-b063-f9334405d60a",
"topic": "conversation.admin.noted",
"delivery_status": "retry",
"delivery_attempts": 2,
"delivered_at": 0,
"first_sent_at": 1483650448,
"created_at": 1483650387,
"self": null
}

【问题讨论】:

  • 你可以接受一个对象作为参数:public void Post([FromBody] object obj){ \\do what ever you want with the obj }

标签: c# json asp.net-mvc-4


【解决方案1】:
  1. 最好的解决方案是就某些预定义的数据结构达成一致,因为这样可以更轻松地检测错误并简化进一步的处理。
  2. 如果您做不到,那么我建议您至少同意一些基本的必填字段并动态处理其他所有内容。要实现它,您必须将您的public void Post([FromBody] AdminNotesModel value) 替换为public void Post([FromBody] String value),然后像Deserialize json with known and unknown fields 中描述的那样手动应用反序列化。我还建议考虑一些可能的动态数据版本控制/键入策略。就像在版本 1 中,附加数据是一些 AdditionalDataVer1 类,而在版本 2 中是 AdditionalDataVer2
  3. 如果您仍然考虑数据的绝对动态架构,那么您只需将收到的字符串值反序列化为某个 dynamicless structured 形式。

【讨论】:

  • 感谢您的建议和解释;非常有帮助。我将在模型课上坚持我的观点
【解决方案2】:

我个人使用 RestSharp 来处理 API 和 HTTP 方法。请看一下:http://restsharp.org/。您可能会发现它非常有用。

【讨论】:

  • 谢谢,约翰。我一定会看看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 2021-09-23
  • 2019-06-11
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
相关资源
最近更新 更多