Created
March 7, 2012 13:34
-
-
Save Stephanvs/1993158 to your computer and use it in GitHub Desktop.
JSON.net Formatter for ASP.NET MVC WEB-API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Net; | |
using System.Net.Http.Formatting; | |
using System.Net.Http.Headers; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Newtonsoft.Json; | |
namespace Global.Serialization | |
{ | |
public class JsonNetFormatter : MediaTypeFormatter | |
{ | |
private JsonSerializerSettings _jsonSerializerSettings; | |
public JsonNetFormatter(JsonSerializerSettings jsonSerializerSettings) | |
{ | |
_jsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings(); | |
// Fill out the mediatype and encoding we support | |
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); | |
Encoding = new UTF8Encoding(false, true); | |
} | |
protected override bool CanReadType(Type type) | |
{ | |
if (type == typeof(IKeyValueModel)) | |
{ | |
return false; | |
} | |
return true; | |
} | |
protected override bool CanWriteType(Type type) | |
{ | |
return true; | |
} | |
protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext) | |
{ | |
// Create a serializer | |
JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings); | |
// Create task reading the content | |
return Task.Factory.StartNew(() => | |
{ | |
using (StreamReader streamReader = new StreamReader(stream, Encoding)) | |
{ | |
using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) | |
{ | |
return serializer.Deserialize(jsonTextReader, type); | |
} | |
} | |
}); | |
} | |
protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext) | |
{ | |
// Create a serializer | |
JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings); | |
// Create task writing the serialized content | |
return Task.Factory.StartNew(() => | |
{ | |
using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, Encoding)) { CloseOutput = false }) | |
{ | |
serializer.Serialize(jsonTextWriter, value); | |
jsonTextWriter.Flush(); | |
} | |
}); | |
} | |
} | |
} |
This is SOOOO much easier:
private async Task<T> CallWebApiAsync<T>(string url, string api, object parameters) {
try {
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync(api, parameters);
if(!response.IsSuccessStatusCode)
throw new Exception("Error " + response.StatusCode + ": " + response.ReasonPhrase);
string sResponse = await response.Content.ReadAsStringAsync();
T ret = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(sResponse);
return ret;
}
catch(Exception ex) {
throw ex;
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Encoding is undefined - line 22.
IKeyValueModel is undefined - line 27.