Trying to serialize a collection of a custom type with an overloaded Equals(object obj)
method. I am using Newtonsoft.Json.JsonConvert.SerializeObject(object value)
to achieve this.
This is my abstract base view model from which the view model in question inherits:
public abstract class BaseCollectibleViewModel
{
protected abstract bool CompareParameters(object item);
protected abstract List<int> GetParameters();
public override bool Equals(object obj)
{
if (CompareParameters(obj))
{
return true;
}
return false;
}
public override int GetHashCode()
{
int hash = 13;
foreach (var parameter in GetParameters())
{
hash = (hash * 7) + parameter.GetHashCode();
}
return hash;
}
public static bool operator ==(BaseCollectibleViewModel a, BaseCollectibleViewModel b)
{
if (a.Equals(b))
{
return true;
}
return false;
}
public static bool operator !=(BaseCollectibleViewModel a, BaseCollectibleViewModel b)
{
if (a.Equals(b))
{
return false;
}
return true;
}
}
This is the actual view model:
public class ImagesViewModel : BaseCollectibleViewModel, ISourceImage
{
public string Name { get; private set; }
public string Type { get; private set; }
[ScriptIgnore]
public Stream Content { get; private set; }
[ScriptIgnore]
private HttpPostedFileBase _file;
[ScriptIgnore]
public HttpPostedFileBase File
{
get
{
return _file;
}
set
{
_file = value;
Name = File.FileName;
Type = File.ContentType;
Content = new MemoryStream();
File.InputStream.CopyTo(Content);
}
}
protected override bool CompareParameters(object obj)
{
var temp = obj as ImagesViewModel;
if(temp == null)
{
return false;
}
return
(Name == temp.Name &&
Type == temp.Type);
}
protected override List<int> GetParameters()
{
return new List<int>()
{
Name.GetHashCode(),
Type.GetHashCode()
};
}
}
Notice the ScriptIgnore
attributes. I even have one on the private field. The program breaks on the ==
operator of the base class because both of the arguments that get passed are null.
This is the serializing code:
[HttpPost]
public string GetSessionImages()
{
var imagesInSession = _imagesSessionService.GetCollection();
return JsonConvert.SerializeObject(imagesInSession, Formatting.Indented);
}
The screenshot is showing the implementation of the abstract CompareParameters(object obj)
method on the inheriting view model. That stream is the Content
property stream, I have checked. Why is this happening?
EDIT: When not overriding Equals I get a JsonSerializationException
stating:
{"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'."}
EDIT 2: Per dbc's comment I have replaced the attribute [ScriptIgnore]
with [JsonIgnore]
and the code worked to an extent.
However, I had to comment out the operator implementations because the '==' operator would be passed a null
value as the BaseCollectibleViewModel b
argument.