2017-01-06 70 views
1

解析复杂的JSON对象的最佳做法是什么?在这种情况下,它将发布到控制器操作?在C中解析嵌套和复杂的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": "[email protected]" 
}, 
"assignee": { 
"type": "admin", 
"id": "848395", 
"name": "Linda", 
"email": "[email protected]" 
}, 
"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 
} 
+0

您可以接受一个对象作为参数: '公共无效后([FromBody] obj对象){ \\你想用OBJ 什么都}' – DomeTune

回答

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表单。
+0

谢谢,建议和解释;很有帮助。我会用模特班坚持我的枪支 – Slinky

0

我个人使用RestSharp与API和HTTP方法工作。请看看:http://restsharp.org/。你可能会觉得它非常有用。

+0

谢谢你,约翰。我会肯定的看一下 – Slinky