public void ToJson_ValidComplexObject_ReturnsJson() { var item = Helper.GetComplexFake(); string result = JSerializer.ToJson(item); Assert.IsTrue(result.Length > 0); }
public GOC() { _webServiceCache = new WebServiceClientCache(); _loggerStandard = new Logger(); _xSerializer = new XSerializer(); _jSerializer = new JSerializer(); _csvSerializer = new CsvSerializer(); _encoding = Encoding.Default; }
public void FromJson_ValidComplexJson_ReturnsObject() { var item = Helper.GetComplexFake(); string json = JSerializer.ToJson(item); var fromJsonObj = JSerializer.FromJson <ComplexFake>(json); Assert.True(fromJsonObj != null); }
static JSerializer CreateDefault() { var s = new JSerializer() { EnabledCamelCaseName = true }; return(s); }
public async Task Send(IWsMessage message, CancellationToken cancellationToken = default) { await EnsureSocketConnection(); var json = JSerializer.Serialize(message); var data = Encoding.UTF8.GetBytes(json); var buffer = new ArraySegment <byte>(data); await _socket.SendAsync(buffer, WebSocketMessageType.Text, true, cancellationToken); }
/// <summary> /// 提供一个 <see cref="JSerializer"/>,初始化一个 <see cref="JsonSerializer"/> 类的新实例。 /// </summary> /// <param name="JSerializer"></param> public JsonSerializer(JSerializer JSerializer) { if (JSerializer == null) { throw new ArgumentNullException(nameof(JSerializer)); } this._serializer = JSerializer; }
/// <summary> /// Envia o Request para o servidor informando o tipo /// </summary> /// <typeparam name="TResponse">Objeto de retorno a ser deserializado do json</typeparam> /// <param name="method">Metodo do Request</param> /// <param name="RequestHeader">Cabeçalhos do Request</param> /// <param name="body">Conteudo do corpo do request. No caso do POST</param> /// <returns></returns> private async Task <Response> ExecuteRequestAsync <TResponse>(string method, List <KeyValuePair <string, string> > RequestHeader, object body = null) where TResponse : new() { HttpResponseMessage response = new HttpResponseMessage(new HttpStatusCode()); try { HttpRequestMessage request = new HttpRequestMessage(method: GetMethod(), requestUri: this.EndPoint) { }; //Define os headers informados client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpeg")); if (body != null) { request.Content = (HttpContent)body; } //foreach (var hdr in RequestHeader) //{ // request.Headers.TryAddWithoutValidation(hdr.Key, hdr.Value); //} if (RequestHeader != null) { RequestHeader.ForEach(hdr => request.Headers.Add(hdr.Key, hdr.Value)); } //**** Metodo Resposavel por enviar o Request Assincrono response = await client.SendAsync(request); //Serializa o json retornado var ResponseObject = JSerializer.ConvertStringToObject <TResponse>(response.Content.ReadAsStringAsync().Result); return(await Task.FromResult( new Response() { Status = response.StatusCode, Description = response.ReasonPhrase, Data = ResponseObject, HttpResponse = response })); HttpMethod GetMethod() => method == "GET" ? HttpMethod.Get : HttpMethod.Post; } catch (Exception e) { Console.WriteLine(e); throw; } }
public GOCWindows() { _settingsCache = new SettingsCache(); _webServiceCache = new WebServiceClientCache(); _databaseCache = new DatabaseCacheWindows(); _logger = new LoggerWindows(); _xSerializer = new XSerializer(); _jSerializer = new JSerializer(); _csvSerializer = new CsvSerializer(); _encoding = Encoding.Default; }
protected virtual async Task <T> GetResponseItem <T>(string path, HttpResponseMessage response) { var json = await GetResponseString(response); if (response.StatusCode != HttpStatusCode.OK) { throw new RestServiceException(GetRestServiceExceptionMessage(path, response.StatusCode)); } return(JSerializer.Deserialize <T>(json)); }
public async Task Send(IWsMessage message, CancellationToken cancellationToken = default) { await EnsureSocketConnection(); await Task.Run(() => _client.Send(JSerializer.Serialize(message)), cancellationToken); if (_configuration.ReconnectEnabled && _configuration.ResubscribeOnReconnect) { _subscriptions.Push(message); } }
internal virtual async Task <TO> Post <TI, TO>(string path, TI payload, CancellationToken cancellationToken = default) { var request = new HttpRequestMessage(HttpMethod.Post, GetRequestUrl(path)); if (payload != null) { request.Content = new StringContent(JSerializer.Serialize(payload), Encoding.UTF8, "application/json"); } var client = EnsureHttpClientCreated(); var response = await client.SendAsync(request, cancellationToken); return(await GetResponseItem <TO>(path, response)); }
// Helper method that recursively convert individual items in the old array private static bool AddItemToList(IList oldList, IList newList, Type elementType, JSerializer serializer, bool throwOnError) { object convertedObject; foreach(Object propertyValue in oldList) { if(!ConvertObjectToTypeMain(propertyValue, elementType, serializer, throwOnError, out convertedObject)) { return false; } newList.Add(convertedObject); } return true; }
internal virtual async Task <T> Post <T>(string path, object payload, IDictionary <string, string> query = null, IDictionary <string, string> customHeaders = null, CancellationToken cancellationToken = default) { var request = new HttpRequestMessage(HttpMethod.Post, BuildUri(path, query)); if (payload != null) { var body = JSerializer.Serialize(payload); request.Content = new StringContent(body, Encoding.UTF8, "application/json"); } FillRequestHeaders(request, customHeaders); using (var response = await _client.SendAsync(request, cancellationToken)) return(await GetResponseItem <T>(response)); }
protected override async Task <T> GetResponseItem <T>(string path, HttpResponseMessage response) { var json = await GetResponseString(response); if (response.StatusCode != HttpStatusCode.OK) { var errorResponse = JSerializer.Deserialize <ErrorResponse>(json); if (errorResponse == null) { throw new RestServiceException(GetRestServiceExceptionMessage(path, response.StatusCode)); } throw new RestServiceException(errorResponse.Payload.Message, errorResponse); } return(JSerializer.Deserialize <T>(json)); }
// Helper method that assigns the propertyValue to object o's member (memberName) private static bool AssignToProperty(TypeMapper typeMapper, object propertyValue, object o, string memberName, JSerializer serializer, bool throwOnError) { var dictionary = o as IDictionary; // if o is already an idictionary, assign the value to the dictionary if(dictionary != null) { if(!ConvertObjectToTypeMain(propertyValue, null, serializer, throwOnError, out propertyValue)) { return false; } dictionary[memberName] = propertyValue; return true; } typeMapper[memberName]?.SetValue(o, propertyValue, false); // not a property , so it is ignored return true; }
protected override async Task <T> GetResponseItem <T>(HttpResponseMessage response) { var content = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { var errorResponse = JSerializer.Deserialize <ErrorResponse>(content); if (errorResponse == null) { throw new RestServiceException( GetRestServiceExceptionMessage(response.RequestMessage.RequestUri.ToString(), response.StatusCode, content)); } throw new RestServiceException(errorResponse.Payload.Message, errorResponse); } return(JSerializer.Deserialize <T>(content)); }
static Dictionary <string, string> LoadCookie() { string content = string.Empty; if (File.Exists(CookieName)) { content = File.ReadAllText(CookieName, Encoding.UTF8); } if (!string.IsNullOrEmpty(content)) { Dictionary <string, string> temp = JSerializer.Deserialize <Dictionary <string, string> >(content); if (null != temp) { return(temp); } } return(new Dictionary <string, string>()); }
private async Task <Response> ExecuteRequestAsync <TResponse>(string method, List <KeyValuePair <string, string> > RequestHeader, object body = null) where TResponse : new() { try { IRestRequest request = new RestRequest(EndPoint, GetMethod(), DataFormat.Json); IRestResponse <TResponse> response = new RestResponse <TResponse>(); //Define os cabeçalhos do request, caso tenha if (RequestHeader != null) { RequestHeader.ForEach(hdr => request.AddHeader(hdr.Key, hdr.Value)); } if (body != null) { request.AddParameter("body", body, ParameterType.RequestBody); } //**** Metodo Resposavel por enviar o Request Assincrono response = client.Execute <TResponse>(request); var ResponseObject = JSerializer.ConvertStringToObject <TResponse>(response.Content); return(await Task.FromResult( new Response() { Status = response.StatusCode, Description = response.StatusDescription, Data = ResponseObject, HttpResponse = response })); //C# 6.0 - Metodo Local. Visivel somente no escopo dessa função Method GetMethod() => method == "GET" ? Method.GET : Method.POST; } catch (Exception e) { Console.WriteLine(e); throw; } }
private IWsMessage DeserializeMessage(string message) { var eventType = JSerializer.Deserialize <WsMessage>(message).Event; switch (eventType) { case EventType.OrderBook: return(JSerializer.Deserialize <OrderBookMessage>(message)); case EventType.Candle: return(JSerializer.Deserialize <CandleMessage>(message)); case EventType.InstrumentInfo: return(JSerializer.Deserialize <InstrumentInfoMessage>(message)); case EventType.Error: return(JSerializer.Deserialize <ErrorMessage>(message)); default: throw new ArgumentException(nameof(eventType)); } }
public void FromJson_Null_Throws() { string json = null; Assert.Throws <ArgumentException>(() => JSerializer.FromJson <SimpleFake>(json)); }
public void FromJson_InValidJson_Throws() { string json = "this is not json"; Assert.Throws <JsonReaderException>(() => JSerializer.FromJson <SimpleFake>(json)); }
public void ToJson_InvalidObject_Throws() { SimpleFake fake = null; Assert.Throws <ArgumentException>(() => JSerializer.ToJson(fake)); }
static void SaveCookie() { File.WriteAllText(CookieName, JSerializer.SerializeToString(mCookie), Encoding.UTF8); }
public static T FromJson <T>(this string json) { Check.Argument.IsNotEmpty(json, "json"); return(JSerializer.Deserialize <T>(json)); }
public static string ToJson <T>(this T instance) { Check.Argument.IsNotNull(instance, "instance"); return(JSerializer.Serialize(instance)); }
internal static object ConvertObjectToType(object o, Type type, JSerializer serializer) { object convertedObject; ConvertObjectToTypeMain(o, type, serializer, true, out convertedObject); return convertedObject; }
// Method that converts an IDictionary<string, object> to an object of the right type private static bool ConvertDictionaryToObject(IDictionary<string, object> dictionary, Type type, JSerializer serializer, bool throwOnError, out object convertedObject) { // The target type to instantiate. Type targetType = type; object s; string serverTypeName = null; object o = dictionary; // Check if __serverType exists in the dictionary, use it as the type. if(dictionary.TryGetValue(JSerializer.ServerTypeFieldName, out s)) { // Convert the __serverType value to a string. if(!ConvertObjectToTypeMain(s, typeof(String), serializer, throwOnError, out s)) { convertedObject = false; return false; } serverTypeName = (string)s; if(serverTypeName != null) { // If we don't have the JavaScriptTypeResolver, we can't use it if(serializer.TypeResolver != null) { // Get the actual type from the resolver. targetType = serializer.TypeResolver.ResolveType(serverTypeName); // In theory, we should always find the type. If not, it may be some kind of attack. if(targetType == null) { if(throwOnError) { throw new InvalidOperationException(); } convertedObject = null; return false; } } // Remove the serverType from the dictionary, even if the resolver was null dictionary.Remove(JSerializer.ServerTypeFieldName); } } JConverter converter = null; if(targetType != null && serializer.ConverterExistsForType(targetType, out converter)) { try { convertedObject = converter.Deserialize(dictionary, targetType, serializer); return true; } catch { if(throwOnError) { throw; } convertedObject = null; return false; } } // Instantiate the type if it's coming from the __serverType argument. if(serverTypeName != null || IsClientInstantiatableType(targetType, serializer)) { // First instantiate the object based on the type. o = Activator.CreateInstance(targetType); } // Use a different collection to avoid modifying the original during keys enumeration. List<String> memberNames = new List<String>(dictionary.Keys); // Try to handle the IDictionary<K, V> case if(IsGenericDictionary(type)) { Type keyType = type.GetGenericArguments()[0]; if(keyType != typeof(string) && keyType != typeof(object)) { if(throwOnError) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_DictionaryTypeNotSupported, type.FullName)); } convertedObject = null; return false; } Type valueType = type.GetGenericArguments()[1]; IDictionary dict = null; if(IsClientInstantiatableType(type, serializer)) { dict = (IDictionary)Activator.CreateInstance(type); } else { // Get the strongly typed Dictionary<K, V> Type t = _dictionaryGenericType.MakeGenericType(keyType, valueType); dict = (IDictionary)Activator.CreateInstance(t); } if(dict != null) { foreach(string memberName in memberNames) { object memberObject; if(!ConvertObjectToTypeMain(dictionary[memberName], valueType, serializer, throwOnError, out memberObject)) { convertedObject = null; return false; } dict[memberName] = memberObject; } convertedObject = dict; return true; } } // Fail if we know we cannot possibly return the required type. if(type != null && !type.IsAssignableFrom(o.GetType())) { if(!throwOnError) { convertedObject = null; return false; } ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, s_emptyTypeArray, null); if(constructorInfo == null) { throw new MissingMethodException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_NoConstructor, type.FullName)); } throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_DeserializerTypeMismatch, type.FullName)); } var typeMapper = TypeMapper.Create(o.GetType()); foreach(string memberName in memberNames) { object propertyValue = dictionary[memberName]; // Assign the value into a property or field of the object if(!AssignToProperty(typeMapper, propertyValue, o, memberName, serializer, throwOnError)) { convertedObject = null; return false; } } convertedObject = o; return true; }
internal static bool TryConvertObjectToType(object o, Type type, JSerializer serializer, out object convertedObject) { return ConvertObjectToTypeMain(o, type, serializer, false, out convertedObject); }
// Is this a type for which we want to instantiate based on the client stub internal static bool IsClientInstantiatableType(Type t, JSerializer serializer) { // Abstract classes and interfaces can't be instantiated // if(t == null || t.IsAbstract || t.IsInterface || t.IsArray) return false; // Even though 'object' is instantiatable, it is never useful to do this if(t == typeof(object)) return false; // Return true if a converter is registered for the given type, so the converter // can generate code on the client to instantiate it. JConverter converter = null; if(serializer.ConverterExistsForType(t, out converter)) { return true; } // Value types are okay (i.e. structs); if(t.IsValueType) { return true; } // Ignore types that don't have a public default ctor ConstructorInfo constructorInfo = t.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, s_emptyTypeArray, null); if(constructorInfo == null) return false; return true; }
private static bool ConvertObjectToTypeMain(object o, Type type, JSerializer serializer, bool throwOnError, out object convertedObject) { // If it's null, there is nothing to convert if(o == null) { // need to special case Char, as we convert \0 to null if(type == typeof(char)) { convertedObject = '\0'; return true; } // Throw if its a value type and not a nullable if(IsNonNullableValueType(type)) { if(throwOnError) { throw new InvalidOperationException(AtlasWeb.JSON_ValueTypeCannotBeNull); } else { convertedObject = null; return false; } } convertedObject = null; return true; } // simply return the current object if the current type is same as return type. if(o.GetType() == type) { convertedObject = o; return true; } // otherwise use the converters to convert object into target type. return ConvertObjectToTypeInternal(o, type, serializer, throwOnError, out convertedObject); }
// Method that converts client array to the request type. It handles the following cases: // 1. type is not passed in - An ArrayList will be returned. // 2. type is an array - An array of the right type will be returned. // 3. type is an abstract collection interface, e.g. IEnumerable, ICollection - // An ArrayList will be returned. // 4. type is an generic abstract collection interface, e.g. IEnumerable<T> - // An List<T> will be returned. // 5. type is a concrete type that implements IList - // The type will be instantiated and returned. // Otherwise we throw InvalidOperationException. private static bool ConvertListToObject(IList list, Type type, JSerializer serializer, bool throwOnError, out IList convertedList) { // Add the items into an ArrayList then convert to custom type when // 1. Type is null or typeof(Object) // 2. Type is an Array, in which case we call ArrayList.ToArray(type) or // 3. Type is already an ArrayList if(type == null || type == typeof(Object) || IsArrayListCompatible(type)) { Type elementType = typeof(Object); if(type != null && type != typeof(Object)) { elementType = type.GetElementType(); } ArrayList newList = new ArrayList(); // Add the items to the new List and recursive into each item. if(!AddItemToList(list, newList, elementType, serializer, throwOnError)) { convertedList = null; return false; } if(type == typeof(ArrayList) || type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection)) { convertedList = newList; return true; } convertedList = newList.ToArray(elementType); return true; } // Add the items into an List<T> then convert to the custom generic type when // 1. Type is a generic collection type // 2. Type only has one generic parameter, eg. List<string> vs MyCustom<T, V> // 3. Type implements IEnumerable<T> else if(type.IsGenericType && type.GetGenericArguments().Length == 1) { // gets the T of List<T> as the elementType Type elementType = type.GetGenericArguments()[0]; // Get the strongly typed IEnumerable<T> Type strongTypedEnumerable = _enumerableGenericType.MakeGenericType(elementType); // Make sure the custom type can be assigned to IEnumerable<T> if(strongTypedEnumerable.IsAssignableFrom(type)) { // Get the strongly typed List<T> Type t = _listGenericType.MakeGenericType(elementType); // Create the List<T> instance or a MyList<T> IList newList = null; if(IsClientInstantiatableType(type, serializer) && typeof(IList).IsAssignableFrom(type)) { newList = (IList)Activator.CreateInstance(type); } else { // If this is MyList<T> and we can't assign to it, throw if(t.IsAssignableFrom(type)) { if(throwOnError) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_CannotCreateListType, type.FullName)); } else { convertedList = null; return false; } } newList = (IList)Activator.CreateInstance(t); } // Add the items to the new List and recursive into each item. if(!AddItemToList(list, newList, elementType, serializer, throwOnError)) { convertedList = null; return false; } convertedList = newList; return true; } } // If the custom type implements IList and it's instantiable. Use that type. else if(IsClientInstantiatableType(type, serializer) && typeof(IList).IsAssignableFrom(type)) { IList newList = (IList)Activator.CreateInstance(type); // Add the items to the new List and recursive into each item. if(!AddItemToList(list, newList, null, serializer, throwOnError)) { convertedList = null; return false; } convertedList = newList; return true; } if(throwOnError) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, AtlasWeb.JSON_ArrayTypeNotSupported, type.FullName)); } else { convertedList = null; return false; } }
// Helper method that converts the object to the corresponding type using converters. // Items in IDictionary<string, object> and ArrayList needs to be converted as well. // Note this method does not invoke the custom converter for deserialization. private static bool ConvertObjectToTypeInternal(object o, Type type, JSerializer serializer, bool throwOnError, out object convertedObject) { // First checks if the object is an IDictionary<string, object> IDictionary<string, object> dictionary = o as IDictionary<string, object>; if(dictionary != null) { return ConvertDictionaryToObject(dictionary, type, serializer, throwOnError, out convertedObject); } // If it is an IList try to convert it to the requested type. IList list = o as IList; if(list != null) { IList convertedList; if(ConvertListToObject(list, type, serializer, throwOnError, out convertedList)) { convertedObject = convertedList; return true; } else { convertedObject = null; return false; } } // simply return the current object if // 1) the caller does not specify the return type. // 2) if the current type is same as return type. if(type == null || o.GetType() == type) { convertedObject = o; return true; } // Otherwise use the type converter to convert the string to the target type. TypeConverter converter = TypeDescriptor.GetConverter(type); // Use the memberType's converter to directly conver if supported. if(converter.CanConvertFrom(o.GetType())) { try { convertedObject = converter.ConvertFrom(null, CultureInfo.InvariantCulture, o); return true; } catch { if(throwOnError) { throw; } else { convertedObject = null; return false; } } } // Otherwise if the target type can be converted from a string // 1. first use the propertyValue's converter to convert object to string, // 2. then use the target converter to convert the string to target type. if(converter.CanConvertFrom(typeof(String))) { try { string s; if(o is DateTime) { // when converting from DateTime it is important to use the 'u' format // so it contains the 'Z' indicating that it is UTC time. // If converting to DateTimeOffset this ensures the value is correct, since otherwise // the deafult offset would be assumed, which is the server's timezone. s = ((DateTime)o).ToUniversalTime().ToString("u", CultureInfo.InvariantCulture); } else { TypeConverter propertyConverter = TypeDescriptor.GetConverter(o); s = propertyConverter.ConvertToInvariantString(o); } convertedObject = converter.ConvertFromInvariantString(s); return true; } catch { if(throwOnError) { throw; } else { convertedObject = null; return false; } } } // We can't convert object o to the target type, but perhaps o can be // assigned directly to type? if(type.IsAssignableFrom(o.GetType())) { convertedObject = o; return true; } // Nothing works if(throwOnError) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.JSON_CannotConvertObjectToType, o.GetType(), type)); } else { convertedObject = null; return false; } }