2017-01-06 109 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