/// <summary> /// During deserialization, reads the JSON representation of the object and handles accordingly, whether of type array or object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> from which to read.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer, <see cref="JsonSerializer"/></param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { switch (reader.TokenType) { case JsonToken.StartArray: { // consume & discard the empty array JArray array = JArray.Load(reader); if (array.Any()) { throw new JsonSerializationException("Expected empty array."); } return(null); } case JsonToken.StartObject: { JsonContract contract = serializer.ContractResolver.ResolveContract(objectType); existingValue = existingValue ?? contract.DefaultCreator(); serializer.Populate(reader, existingValue); return(existingValue); } default: return(null); } }
/// <summary> /// Creates and populates the root object using the default settings. /// </summary> private static object CreateRootObject(JToken token, JsonContract contract, JsonSerializer serializer) { var value = contract.DefaultCreator(); serializer.Populate(token.CreateReader(), value); return(value); }
private static object UndefaultValue(Type objectType, object existingValue, JsonContract contract) { if (existingValue == null && objectType.IsValueType && Nullable.GetUnderlyingType(objectType) == null) { existingValue = contract.DefaultCreator(); } return(existingValue); }
public static object Create(this JsonSerializer serializer, Type type) { JsonContract contract = serializer.ContractResolver.ResolveContract(type); if (contract.DefaultCreator == null) { throw new JsonSerializationException("Unable to find a default constructor to use for type '{0}'." .Fmt(type.GetFullName())); } return(contract.DefaultCreator()); }
private bool TryParseAsRelationship(JsonContract contract, object value, out object relationshipObj) { switch (contract.Converter) { case ResourceObjectConverter _: relationshipObj = Relationship.Create(value); return(true); case ResourceObjectListConverter _: relationshipObj = Relationship.Create(value as IEnumerable <object>); return(true); case ResourceRelationshipConverter _: relationshipObj = value ?? contract.DefaultCreator(); return(true); default: relationshipObj = null; return(false); } }