Why JSON DeSerialization fails in C#? - json

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.

Related

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;
}
}

System.MethodAccessException by JsonConvert.DeserializeObject()

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?

MvvmCross: Deserilization Error for JSON

I'm trying to create a simple application through Lesson 6 in N+1 Days of MvvmCross application sample. But its failed in SimpleRestService while converting json Data serialization.
private T Deserialize<T>(string responseBody)
{ // Error is here for deserilizing
var toReturn = _jsonConverter.DeserializeObject<T>(responseBody);
return toReturn;
}
My Json data through Browser:
[{"Desc":"All","Id":"0"},{"Desc":"Assigned","Id":"2"},{"Desc":"In Progress","Id":"3"},{"Desc":"Resolved","Id":"4"},{"Desc":"Closed","Id":"5"},{"Desc":"Hold","Id":"6"},{"Desc":"低","Id":"8"},{"Desc":"Waiting Approval","Id":"9"},{"Desc":"Cancelled","Id":"10"},{"Desc":"Not Resolved","Id":"8"}]
My Json data in application at responsebody:
[{\"Desc\":\"All\",\"Id\":\"0\"},{\"Desc\":\"Assigned\",\"Id\":\"2\"},{\"Desc\":\"In Progress\",\"Id\":\"3\"},{\"Desc\":\"Resolved\",\"Id\":\"4\"},{\"Desc\":\"Closed\",\"Id\":\"5\"},{\"Desc\":\"Hold\",\"Id\":\"6\"},{\"Desc\":\"低\",\"Id\":\"8\"},{\"Desc\":\"Waiting Approval\",\"Id\":\"9\"},{\"Desc\":\"Cancelled\",\"Id\":\"10\"},{\"Desc\":\"Not Resolved\",\"Id\":\"8\"}]
Error Message shows as :
{Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Book.Core.Services.BookSearchResult'.
The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList.
To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Path '', line 1, position 1.
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract) [0x00000] in :0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String reference) [0x00000] in :0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, System.Object existingValue) [0x00000] in :0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.JsonConverter converter, Newtonsoft.Json.Serialization.JsonContainerContract containerContract) [0x00000] in :0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in :0
at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in :0
at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in :0 etc.. }
My Code part:
Class Declaration:
public class BookSearchItem
{
public string Desc { get; set; }
public string Id { get; set; }
}
public class BookSearchResult
{
public List<BookSearchItem> items { get; set; }
}
Binding Declaration:
public void StartSearchAsync(string whatFor, Action<BookSearchResult> success, Action<Exception> error)
{
string address = string.Format("http://192.168.0.76/eFACiLiTYPhone/MobileService/WinPhoneWCFService.svc/callstatustesting");
_simpleRestService.MakeRequest<BookSearchResult>(address,"GET", success, error);
}
Simple Rest Service For Common:
public class SimpleRestService :ISimpleRestService
{
private readonly IMvxJsonConverter _jsonConverter;
public SimpleRestService(IMvxJsonConverter jsonConverter)
{
_jsonConverter = jsonConverter;
}
public void MakeRequest<T>(string requestUrl, string verb, Action<T> successAction, Action<Exception> errorAction)
{
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = verb;
request.Accept = "application/json";
MakeRequest(
request,
(response) =>
{
if (successAction != null)
{
T toReturn;
try
{
toReturn = Deserialize<T>(response);
}
catch (Exception ex)
{
errorAction(ex);
return;
}
successAction(toReturn);
}
},
(error) =>
{
if (errorAction != null)
{
errorAction(error);
}
}
);
}
private void MakeRequest(HttpWebRequest request, Action<string> successAction, Action<Exception> errorAction)
{
request.BeginGetResponse(token =>
{
try
{
using (var response = request.EndGetResponse(token))
{
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream);
successAction(reader.ReadToEnd());
}
}
}
catch (WebException ex)
{
Mvx.Error("ERROR: '{0}' when making {1} request to {2}", ex.Message, request.Method, request.RequestUri.AbsoluteUri);
errorAction(ex);
}
}, null);
}
private T Deserialize<T>(string responseBody)
{
var toReturn = _jsonConverter.DeserializeObject<T>(responseBody);
return toReturn;
}
}
You have to use the correct T for your Json call - you can't simply use BookSearchResult for all Json calls.
You can use tools like http://json2csharp.com/ to generate the CSharp classes for you - e.g.
public class RootObject
{
public string Desc { get; set; }
public string Id { get; set; }
}
which you can then use as:
var myItems = service.Deserialize<List<RootObject>>(jsonText);

Asp.Net Web Api & JSON.Net - Deserialize body into .Net generic objects

I want to deserialize the body into .net classes (dictionary and list).
(so my code is transparent for xml and json)
public HttpResponseMessage Post([FromBody]IDictionary<string, object> body)
{
}
Currently I use a converter to handle nested dictionary deserialization.
class IDictionaryConverter : CustomCreationConverter<IDictionary<string, object>>
{
public override IDictionary<string, object> Create(Type objectType)
{
return new Dictionary<string, object>();
}
public override bool CanConvert(Type objectType)
{
// in addition to handling IDictionary<string, object>
// we want to handle the deserialization of dict value
// which is of type object
return objectType == typeof(object) || base.CanConvert(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.Null)
return base.ReadJson(reader, objectType, existingValue, serializer);
// if the next token is not an object
// then fall back on standard deserializer (strings, numbers etc.)
return serializer.Deserialize(reader);
}
}
But nested JLists are not converted to List.
Maybe I can create a IListConverter, but is there an better way to do this?
I want in my web api only one code. not: if json do that, if xml do that...
This solves my problem:
class IDictionaryConverter : CustomCreationConverter<IDictionary<string, object>>
{
public override IDictionary<string, object> Create(Type objectType)
{
return new Dictionary<string, object>();
}
public override bool CanConvert(Type objectType)
{
// in addition to handling IDictionary<string, object>
// we want to handle the deserialization of dict value
// which is of type object
return objectType == typeof(object) || base.CanConvert(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.Null)
return base.ReadJson(reader, objectType, existingValue, serializer);
if (reader.TokenType == JsonToken.StartArray)
return serializer.Deserialize<IList<object>>(reader);
// if the next token is not an object
// then fall back on standard deserializer (strings, numbers etc.)
return serializer.Deserialize(reader);
}
}

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?