Blog
Using Json.Net to deserialize for WebApi methods
Having battled with the problems of the default Json deserialiser in WebApi, I wanted to use Json.Net instead.
The way I ultimately want to do this would be to pass the model in as a parameter and have it deserialized by Json.Net automatically, which by the looks of it is done with a MediaFormatter (presumably that is what I'll end up doing once I've looked into it further).
Public Sub Post(model As MyModelView) As String 'Do what you need to store the data Return "OK" End Sub
The following solution isn't quite as pretty, but is a simple way to deserialize incoming data to WebApi methods, using Json.Net:
1. Create an Extension method within a Module
Imports System.Runtime.CompilerServices Module Extensions 'Deserializes the specified Request content from Json to the specified type <Extension> Function FromJson(Of T)(ByVal Request As System.Net.Http.HttpRequestMessage) As T Dim data As String = Request.Content.ReadAsStringAsync().Result Return Newtonsoft.Json.JsonConvert.DeserializeObject(Of T)(data) End Function End Module
2. Deserialise instead of using parameters
Use the simple extension above instead of having a method parameter:
Public Sub Post() As String Dim model As MyModelView = Request.FromJson(Of MyModelView)() 'Do what you need to store the data Return "OK" End SubBy Theo Gray on March 15, 2013 | Permalink | Comment
Reader Comments
Skip to form
There are currently no comments about this article.