LitJsonEncoder.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #if !BESTHTTP_DISABLE_SIGNALR_CORE
  2. using System;
  3. using BestHTTP.PlatformSupport.Memory;
  4. using BestHTTP.JSON.LitJson;
  5. namespace BestHTTP.SignalRCore.Encoders
  6. {
  7. public sealed class LitJsonEncoder : BestHTTP.SignalRCore.IEncoder
  8. {
  9. public LitJsonEncoder()
  10. {
  11. BestHTTP.JSON.LitJson.JsonMapper.RegisterImporter<int, long>((input) => input);
  12. BestHTTP.JSON.LitJson.JsonMapper.RegisterImporter<long, int>((input) => (int)input);
  13. BestHTTP.JSON.LitJson.JsonMapper.RegisterImporter<double, int>((input) => (int)(input + 0.5));
  14. BestHTTP.JSON.LitJson.JsonMapper.RegisterImporter<string, DateTime>((input) => Convert.ToDateTime((string)input).ToUniversalTime());
  15. BestHTTP.JSON.LitJson.JsonMapper.RegisterImporter<double, float>((input) => (float)input);
  16. BestHTTP.JSON.LitJson.JsonMapper.RegisterImporter<string, byte[]>((input) => Convert.FromBase64String(input));
  17. BestHTTP.JSON.LitJson.JsonMapper.RegisterExporter<float>((f, writer) => writer.Write((double)f));
  18. }
  19. public T DecodeAs<T>(BufferSegment buffer)
  20. {
  21. using (var reader = new System.IO.StreamReader(new System.IO.MemoryStream(buffer.Data, buffer.Offset, buffer.Count)))
  22. {
  23. return JsonMapper.ToObject<T>(reader);
  24. }
  25. }
  26. public PlatformSupport.Memory.BufferSegment Encode<T>(T value)
  27. {
  28. var json = JsonMapper.ToJson(value);
  29. int len = System.Text.Encoding.UTF8.GetByteCount(json);
  30. byte[] buffer = BufferPool.Get(len + 1, true);
  31. System.Text.Encoding.UTF8.GetBytes(json, 0, json.Length, buffer, 0);
  32. buffer[len] = (byte)JsonProtocol.Separator;
  33. return new BufferSegment(buffer, 0, len + 1);
  34. }
  35. public object ConvertTo(Type toType, object obj)
  36. {
  37. string json = BestHTTP.JSON.LitJson.JsonMapper.ToJson(obj);
  38. return BestHTTP.JSON.LitJson.JsonMapper.ToObject(toType, json);
  39. }
  40. }
  41. }
  42. #endif