System.MethodAccessException by JsonConvert.DeserializeObject() - windows-phone-8

The JsonConvert.DeserializeObject statement of the following code generates the exception:
try
{
string sJOutput = JsonConvert.SerializeObject(dict,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
Debug.WriteLine(sJOutput);
dict = JsonConvert.DeserializeObject<Dictionary<Guid, MyClass>>(sJOutput);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
The exception is the following:
System.MethodAccessException was caught
HResult=-2146233072
Message=Attempt by method 'DynamicClass.lambda_method(System.Runtime.CompilerServices.Closure)' to access method 'System.Xml.Linq.XElement..ctor()' failed.
Source=Anonymously Hosted DynamicMethods Assembly
StackTrace:
at lambda_method(Closure )
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, String id, Boolean& createdFromNonDefaultCreator)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at ...
InnerException:
Could anyone offer a tip on the cause of this?

Related

MVC 5 Razor System.Security.SecurityException

Just created a new application and put the trust level Medium in web.config
<trust level="Medium" />
I need to test the application in Medium trust level because I have to host on shared server.
Now run the application and get error on this line
#Html.ActionLink("XYZ", "Index", "Home", new {area=""}, new {#class="link" })
Here is the complete error:
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
<span class="icon-bar"></span>
</button>
#Html.ActionLink("xyz", "Index", "Home",
new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
Stack Trace:
[SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) +34
System.Security.CodeAccessPermission.Demand() +46
System.Web.HttpContext.System.IServiceProvider.GetService(Type service) +54
System.Web.HttpContextWrapper.GetService(Type serviceType) +13
System.Web.WebPages.UrlRewriterHelper.IsUrlRewriterTurnedOn(HttpContextBase httpContext) +157
System.Web.WebPages.UrlRewriterHelper.WasRequestRewritten(HttpContextBase httpContext) +37
System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath) +229
System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String contentPath) +120
System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues) +324
System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, String protocol, String hostName, String fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues) +100
System.Web.Mvc.HtmlHelper.GenerateLinkInternal(RequestContext requestContext, RouteCollection routeCollection, String linkText, String routeName, String actionName, String controllerName, String protocol, String hostName, String fragment, RouteValueDictionary routeValues, IDictionary`2 htmlAttributes, Boolean includeImplicitMvcValues) +96
System.Web.Mvc.HtmlHelper.GenerateLink(RequestContext requestContext, RouteCollection routeCollection, String linkText, String routeName, String actionName, String controllerName, String protocol, String hostName, String fragment, RouteValueDictionary routeValues, IDictionary`2 htmlAttributes) +71
System.Web.Mvc.HtmlHelper.GenerateLink(RequestContext requestContext, RouteCollection routeCollection, String linkText, String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, IDictionary`2 htmlAttributes) +66
System.Web.Mvc.Html.LinkExtensions.ActionLink(HtmlHelper htmlHelper, String linkText, String actionName, String controllerName, RouteValueDictionary routeValues, IDictionary`2 htmlAttributes) +187
System.Web.Mvc.Html.LinkExtensions.ActionLink(HtmlHelper htmlHelper, String linkText, String actionName, String controllerName, Object routeValues, Object htmlAttributes) +115
ASP._Page_Views_Shared__Layout_cshtml.Execute() in d:\TestProjects\Medium\Medium\Views\Shared\_Layout.cshtml:19
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +270
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +121
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +145
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer) +41
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +335
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +42
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +45
System.Web.WebPages.WebPageBase.Write(HelperResult result) +53
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +178
System.Web.WebPages.WebPageBase.PopContext() +229
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +154
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9742689
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I had the same problem a few weeks ago. My problem with the trust medium level was that my cshtml had a "~" at the javascript tag, like:
<script src="~/Scripts/foo.js"></script>
Removing the "~" simply resolved my problem.
It's a weird error because it points to a Razor declaration instead of the "~" line. Although the "~" is a special Razor symbol in this case.
Hope this might help.

Web API: Failed to serialize the response body for content type

I am working with ASP.NET MVC 5 Web Api.
I am having existing application with many api's.
Recently I have implemented custom JsonConverter which will convert Date as per timezone.
public class CustomInfoConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(CustomType);
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var customType = (CustomType)value;
if (customType == null || null== customType.TimeZone) return;
//DateTime currentDateTime = customType.Date??DateTime.Now;
DateTime currentDateTime = DateTime.SpecifyKind(customType.Date ?? DateTime.Now, DateTimeKind.Unspecified);
DateTime userDateTime = TimeZoneInfo.ConvertTimeFromUtc(currentDateTime, customType.TimeZone);
customType.Date = userDateTime;
JsonSerializer innerSerializer = new JsonSerializer();
foreach (var converter in serializer.Converters.Where(c => !(c is CustomInfoConverter)))
{
innerSerializer.Converters.Add(converter);
}
innerSerializer.Serialize(writer, customType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
After implementing this custom JsonConverter all api are working except one api, which is throwing below exception
{"Message":"An error has occurred.","ExceptionMessage":"The
'ObjectContent`1' type failed to serialize the response body for
content type 'application/json;
charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An
error has occurred.","ExceptionMessage":"Token PropertyName in state
Property would result in an invalid JSON object. Path
'Data.Forms[0]'.","ExceptionType":"Newtonsoft.Json.JsonWriterException","StackTrace":"
at Newtonsoft.Json.JsonWriter.AutoComplete(JsonToken
tokenBeingWritten)\r\n at
Newtonsoft.Json.JsonWriter.InternalWritePropertyName(String name)\r\n
at Newtonsoft.Json.JsonTextWriter.WritePropertyName(String name,
Boolean escape)\r\n at
Newtonsoft.Json.Serialization.JsonProperty.WritePropertyName(JsonWriter
writer)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter
writer, Object value, JsonObjectContract contract, JsonProperty
member, JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter
writer, IEnumerable values, JsonArrayContract contract, JsonProperty
member, JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter
writer, Object value, JsonObjectContract contract, JsonProperty
member, JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter
writer, Object value, JsonObjectContract contract, JsonProperty
member, JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter
jsonWriter, Object value, Type objectType)\r\n at
Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter
jsonWriter, Object value, Type objectType)\r\n at
Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object
value)\r\n at
System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type
type, Object value, Stream writeStream, Encoding
effectiveEncoding)\r\n at
System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type
type, Object value, Stream writeStream, Encoding
effectiveEncoding)\r\n at
System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type
type, Object value, Stream writeStream, HttpContent content)\r\n at
System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type
type, Object value, Stream writeStream, HttpContent content,
TransportContext transportContext, CancellationToken
cancellationToken)\r\n--- End of stack trace from previous location
where exception was thrown ---\r\n at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at
System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()"}}
You can refer to this link for more details.
The problem looks to be that, in certain situations, you are returning from WriteJson() without writing anything, specifically when customType.TimeZone == null:
var customType = (CustomType)value;
if (customType == null || null== customType.TimeZone) return;
Doing so will result in an invalid JSON object, because the property name will already have been written by the caller, resulting in:
{
"customType":
}
Trying to do this results in the exception you are seeing.
Instead, you need to prevent the property itself from being serialized. That's not possible in the converter however, it needs to be done in the containing type.
To avoid serializing a property with a null value, you should set NullValueHandling = NullValueHandling.Ignore in serializer settings, or on the property itself:
public class ContainerClass
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public CustomType CustomType { get; set; }
}
To prevent serializing your property when its TimeZone property is null, you should use conditional property serialization by adding a ShouldSerializeXXX() method to the containing type, where XXX exactly matches your property name:
public class ContainerClass
{
public CustomType CustomType { get; set; }
public bool ShouldSerializeCustomType()
{
return CustomType != null && CustomType.TimeZone != null;
}
}

An item with the same key has already been added on form submit MVC 4

An item with the same key has already been added
Stack Trace:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +10695474
System.Linq.Enumerable.ToDictionary(IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer) +247
System.Linq.Enumerable.ToDictionary(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer) +90
System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +157
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +213
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +88
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +53
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1314
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +416
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Why JSON DeSerialization fails in C#?

I am trying to De-serialize the string using Newtonsoft.Json dll of
RunTime Version
v2.0.50727
Version
4.5.0.0.
Target FrameWork
.Net Framework 2.0
To String:
jsonString ="{\"RelatedExceptions\":[{\"ClassName\":\"System.Web.Services.Protocols.SoapException\",\"Message\":\"Exception of type Microsoft.SharePoint.SoapServer.SoapServerException was thrown.\",\"Data\":{\"code\":{\"Namespace\":\"http://schemas.xmlsoap.org/soap/envelope/\",\"Name\":\"Server\",\"IsEmpty\":false},\"actor\":\"\",\"role\":\"\",\"subCode\":null,\"lang\":\"\"},\"InnerException\":null,\"HelpURL\":null,\"StackTraceString\":\" at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)\\r\\n at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)\\r\\n at abc.Common.SPWebServicesHelper.SPS2003ListsWs.Lists.GetListItems(String listName, String viewName, XmlNode query, XmlNode viewFields, String rowLimit, XmlNode queryOptions) in d:\\\\DeployerWorkingCopy\\\\TzDE2 .net2\\\\abc.Common.SPWebServicesHelper\\\\Web References\\\\SPS2003ListsWs\\\\Reference.cs:line 484\\r\\n at abc.Common.SPHandlerBase.WSWrappers.SPS2003ListsWsWrapper.GetListItems(String serviceUrl, String listName, String viewName, XmlNode query, XmlNode viewFields, String rowLimit, XmlNode queryOptions) in d:\\\\DeployerWorkingCopy\\\\TzDE2 .net2\\\\abc.Common.SPHandlerBase\\\\WebServicesWrappers\\\\SPS2003ListsWsWrapper.cs:line 215\\r\\n at abc.Common.SPS2003Handler.SPS2003ContentsManager.GetListItems(Site site, String listName, String strViewName, XmlNode ndQuery, XmlNode ndViewFields, String strRowLimit, XmlNode ndQueryOptions, String strWebId) in d:\\\\DeployerWorkingCopy\\\\TzDE2 .net2\\\\abc.Common.SPS2003Handler\\\\SPS2003ContentsManager.cs:line 5447\\r\\n at abc.Common.SPS2003Handler.SPSContentsManager.GetListItemCollectionPositionNext(SPList list, Folder folder, Int32 itemCountStartPosition, String orderBy) in d:\\\\DeployerWorkingCopy\\\\TzDE2 .net2\\\\abc.Common.SPS2003Handler\\\\SPSContentsManager.cs:line 8460\\r\\n at abc.Common.SPS2003Handler.SPSContentsManager.GetItemsAndProperties(SPList list, Folder folder, PropertyCollection props, Boolean readVersions, Boolean readOnlyFolders, Boolean readSecurity, Boolean readDiscussionItems) in d:\\\\DeployerWorkingCopy\\\\TzDE2 .net2\\\\abc.Common.SPS2003Handler\\\\SPSContentsManager.cs:line 8569\",\"RemoteStackTraceString\":null,\"RemoteStackIndex\":0,\"ExceptionMethod\":\"8\\nReadResponse\\nSystem.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\\nSystem.Web.Services.Protocols.SoapHttpClientProtocol\\nSystem.Object[] ReadResponse(System.Web.Services.Protocols.SoapClientMessage, System.Net.WebResponse, System.IO.Stream, Boolean)\",\"HResult\":-2146233087,\"Source\":\"System.Web.Services\",\"WatsonBuckets\":null}],\"Resolution\":\"\",\"EntryType\":1,\"Description\":\"Failed to read items of list: http://spportal:33333/_layouts/1033/lstman.aspx\\r\\n\\n \\n\\tList does not exist\\n\\n\\tThe page you selected contains a list that does not exist. It may have been deleted by another user. Click \\\"Home\\\" at the top of the page to return to your Web site.\\n\\t\\n 0x82000006\\n \",\"TimeStamp\":\"2013-05-08T11:45:54.299965+05:45\"}"
Deserialization Method call
JsonConvert.DeserializeObject<ExecutionReportEntry>(jsonString);
Result :-
StackTrace:
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 256
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty(JsonReader reader, Type objectType, JsonContract contract, JsonConverter converter) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 230
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateDictionary(IWrappedDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, String id) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 728
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateAndPopulateDictionary(JsonReader reader, JsonDictionaryContract contract, String id) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 679
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 462
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 245
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty(JsonReader reader, Type objectType, JsonContract contract, JsonConverter converter) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 230
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 126
at Newtonsoft.Json.Serialization.JsonSerializerProxy.DeserializeInternal(JsonReader reader, Type objectType) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerProxy.cs:line 174
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\JsonSerializer.cs:line 461
at Newtonsoft.Json.Serialization.JsonFormatterConverter.Convert(Object value, Type type) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonFormatterConverter.cs:line 62
at System.Runtime.Serialization.SerializationInfo.GetValueNoThrow(String name, Type type)
at System.Exception..ctor(SerializationInfo info, StreamingContext context)
at Void .ctor(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)(Object , Object[] )
at Newtonsoft.Json.Serialization.DefaultContractResolver.<>c__DisplayClass9.<CreateISerializableContract>b__8(Object[] args) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\DefaultContractResolver.cs:line 634
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateISerializable(JsonReader reader, JsonISerializableContract contract, String id) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 865
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 473
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 245
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty(JsonReader reader, Type objectType, JsonContract contract, JsonConverter converter) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 230
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IWrappedCollection wrappedList, JsonReader reader, String reference, JsonArrayContract contract) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 816
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.<>c__DisplayClass1.<CreateAndPopulateList>b__0(IList l, Boolean isTemporaryListReference) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 759
at Newtonsoft.Json.Utilities.CollectionUtils.CreateAndPopulateList(Type listType, Action`2 populateList) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Utilities\CollectionUtils.cs:line 242
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateAndPopulateList(JsonReader reader, String reference, JsonArrayContract contract) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 747
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String reference) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 510
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 247
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueProperty(JsonReader reader, JsonProperty property, JsonConverter propertyConverter, Object target, Boolean gottenCurrentValue, Object currentValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 222
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ResolvePropertyAndConstructorValues(JsonObjectContract contract, JsonReader reader, Type objectType) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 1101
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, ConstructorInfo constructorInfo, String id) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 999
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateAndPopulateObject(JsonReader reader, JsonObjectContract contract, String id) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 968
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 444
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 245
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty(JsonReader reader, Type objectType, JsonContract contract, JsonConverter converter) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 230
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 126
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\JsonSerializer.cs:line 483
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\JsonSerializer.cs:line 461
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\JsonConvert.cs:line 925
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\JsonConvert.cs:line 885
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value) in c:\Dev\Releases\Working\GitHub\Newtonsoft.Json\Src\Newtonsoft.Json\JsonConvert.cs:line 842
at abc.Common.Collection.EsentErEntries`1.GetByKey(Double key) in d:\DeployerWorkingCopy\TzDE2 .net2\abc.Common\Collection\EsentDbWrapper.cs:line 748
Json in a more readable format:
{
"RelatedExceptions": [
{
"ClassName": "System.Web.Services.Protocols.SoapException",
"Message": "Exception of type Microsoft.SharePoint.SoapServer.SoapServerException was thrown.",
"Data": {
"code": {
"Namespace": "http://schemas.xmlsoap.org/soap/envelope/",
"Name": "Server",
"IsEmpty": false
},
"actor": "",
"role": "",
"subCode": null,
"lang": ""
},
"InnerException": null,
"HelpURL": null,
"StackTraceString": " at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)\r\n at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)\r\n at abc.Common.SPWebServicesHelper.SPS2003ListsWs.Lists.GetListItems(String listName, String viewName, XmlNode query, XmlNode viewFields, String rowLimit, XmlNode queryOptions) in d:\\DeployerWorkingCopy\\TzDE2 .net2\\abc.Common.SPWebServicesHelper\\Web References\\SPS2003ListsWs\\Reference.cs:line 484\r\n at abc.Common.SPHandlerBase.WSWrappers.SPS2003ListsWsWrapper.GetListItems(String serviceUrl, String listName, String viewName, XmlNode query, XmlNode viewFields, String rowLimit, XmlNode queryOptions) in d:\\DeployerWorkingCopy\\TzDE2 .net2\\abc.Common.SPHandlerBase\\WebServicesWrappers\\SPS2003ListsWsWrapper.cs:line 215\r\n at abc.Common.SPS2003Handler.SPS2003ContentsManager.GetListItems(Site site, String listName, String strViewName, XmlNode ndQuery, XmlNode ndViewFields, String strRowLimit, XmlNode ndQueryOptions, String strWebId) in d:\\DeployerWorkingCopy\\TzDE2 .net2\\abc.Common.SPS2003Handler\\SPS2003ContentsManager.cs:line 5447\r\n at abc.Common.SPS2003Handler.SPSContentsManager.GetListItemCollectionPositionNext(SPList list, Folder folder, Int32 itemCountStartPosition, String orderBy) in d:\\DeployerWorkingCopy\\TzDE2 .net2\\abc.Common.SPS2003Handler\\SPSContentsManager.cs:line 8460\r\n at abc.Common.SPS2003Handler.SPSContentsManager.GetItemsAndProperties(SPList list, Folder folder, PropertyCollection props, Boolean readVersions, Boolean readOnlyFolders, Boolean readSecurity, Boolean readDiscussionItems) in d:\\DeployerWorkingCopy\\TzDE2 .net2\\abc.Common.SPS2003Handler\\SPSContentsManager.cs:line 8569",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": "8\nReadResponse\nSystem.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\nSystem.Web.Services.Protocols.SoapHttpClientProtocol\nSystem.Object[] ReadResponse(System.Web.Services.Protocols.SoapClientMessage, System.Net.WebResponse, System.IO.Stream, Boolean)",
"HResult": -2146233087,
"Source": "System.Web.Services",
"WatsonBuckets": null
}
],
"Resolution": "",
"EntryType": 1,
"Description": "Failed to read items of list: http://spportal:33333/_layouts/1033/lstman.aspx\r\n\n \n\tList does not exist\n\n\tThe page you selected contains a list that does not exist. It may have been deleted by another user. Click \"Home\" at the top of the page to return to your Web site.\n\t\n 0x82000006\n ",
"TimeStamp": "2013-05-08T11:45:54.299965+05:45"
}
Class
public enum ExecutionReportEntryType
{
Fatal,
Error,
Warning,
Info,
Success
}
public interface IExecutionReportEntry
{
string Description { get; }
ExecutionReportEntryType EntryType { get; }
IList<Exception> RelatedExceptions { get; }
string Resolution { get; set; }
DateTime TimeStamp { get; }
}
public class ExecutionReportEntry : IExecutionReportEntry
{
private readonly List<Exception> _relatedExceptions = new List<Exception>();
public IList<Exception> RelatedExceptions
{
get
{
// Removing the readonly mode as this causes problem during Deserializing process(which is used to store the data into the ESENT database)
return _relatedExceptions;
}
}
public virtual string Resolution
{
get { return string.Empty; }
set { }
}
public ExecutionReportEntryType EntryType { get; private set; }
public string Description { get; private set; }
public DateTime TimeStamp { get; private set; }
public ExecutionReportEntry(ExecutionReportEntryType entryType, string description)
: this(DateTime.Now, entryType, description, null)
{ }
public ExecutionReportEntry(ExecutionReportEntryType entryType, string description, Exception ex)
: this(DateTime.Now, entryType, description, ex)
{ }
[JsonConstructor]
public ExecutionReportEntry(DateTime timeStamp, ExecutionReportEntryType entryType, string description, Exception ex)
{
EntryType = entryType;
Description = description;
TimeStamp = timeStamp;
if (ex != null)
_relatedExceptions.Add(ex);
}
}
The RelatedExceptions property is 'readonly' for the (de)serializer.
Add a set to the property as well.
The same goes for the other private setters.
They need to be public for the serializer to set them.

Deserializing dictionary with derived types using NewtonSoft's Json library

Given the following class structure, which includes a dictionary of derived objects, how can I serialize and deserialize using NewtonSoft’s Json library? When I deserialize, I am getting an exception. It looks like it is having issues reconstituting the dictionary.
[JsonObject(MemberSerialization.OptIn)]
public class GameObject
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public ConcurrentDictionary<string, Component> Components;
public GameObject()
{
Components = new ConcurrentDictionary<string, Component>();
}
}
[JsonObject(MemberSerialization.OptIn)]
public class Component
{
[JsonIgnore] // Ignore circular reference
public GameObject GameObject { get; set; }
public Component()
{
}
}
[JsonObject(MemberSerialization.OptIn)]
public class TestComponent : Component
{
[JsonProperty]
public int MyProperty { get; set; }
public TestComponent()
{
}
}
var originalJson = JsonConvert.SerializeObject(srcObject, Formatting.None,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
});
var newObject = JsonConvert.DeserializeObject<GameObject>(originalJson,
new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
});
Exception on the DeserializeObject call:
System.Reflection.TargetInvocationException was unhandled by user code
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Newtonsoft.Json.Serialization.JsonContract.InvokeOnDeserialized(Object o, StreamingContext context) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonContract.cs:line 135
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateDictionary(IWrappedDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, String id) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 638
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateAndPopulateDictionary(JsonReader reader, JsonDictionaryContract contract, String id) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 593
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 387
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 223
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueProperty(JsonReader reader, JsonProperty property, Object target, Boolean gottenCurrentValue, Object currentValue) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 198
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, String id) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 876
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateAndPopulateObject(JsonReader reader, JsonObjectContract contract, String id) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 846
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 396
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 223
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty(JsonReader reader, Type objectType, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 208
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 120
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonSerializer.cs:line 421
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonSerializer.cs:line 413
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonConvert.cs:line 721
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonConvert.cs:line 683
at MF.Tests.GameServer.ComponentSerializationTests.TestSerializationOfObjectWithComponent() in C: \ComponentSerializationTests.cs:line 119
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=mscorlib
StackTrace:
at System.Collections.Concurrent.ConcurrentDictionary`2.InitializeFromCollection(IEnumerable`1 collection)
at System.Collections.Concurrent.ConcurrentDictionary`2.OnDeserialized(StreamingContext context)
InnerException:
Update:
If change the ConcurrentDictionary to a List or a Dictionary, the code works as expected.
What am I doing wrong?