[英]Newtonsoft json.net deserialization NullReferenceException
I have a simple JSON generated with WCF Rest client, but when I try to deserialize a response I get an error NullReferenceException
in JSON.Net. 我有一个使用WCF Rest客户端生成的简单JSON,但是当我尝试反序列化响应时,我在JSON.Net中收到错误NullReferenceException
。 I have following JSON: 我有以下JSON:
{"Code":-2146232800,"ExceptionType":"IOException","Message":"Msg","Stacktrace":"Some"}
And following class: 下课:
[DataContract]
public class FileUploadError
{
public FileUploadError(Exception exception)
{
Code = exception.HResult;
ExceptionType = exception.GetType().Name;
Message = GetMessage(exception);
Stacktrace = exception.StackTrace;
if (exception.Data.Count > 0)
{
Data = string.Join(Environment.NewLine, exception.Data.Cast<DictionaryEntry>().Select(x => x.Key + "=" + x.Value));
}
}
private string GetMessage(Exception exception)
{
if (exception.InnerException == null)
{
return exception.Message;
}
const string delimiter = "->";
var sb = new StringBuilder(1024);
for (var ex = exception; ex != null; ex = ex.InnerException)
{
sb.Append(ex.Message).Append(delimiter);
}
sb.Length -= delimiter.Length;
return sb.ToString();
}
[DataMember(IsRequired = true)]
[JsonProperty("Code", NullValueHandling = NullValueHandling.Ignore)]
public int Code { get; set; }
[DataMember(IsRequired = true)]
[JsonProperty("ExceptionType", NullValueHandling = NullValueHandling.Ignore)]
public string ExceptionType { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty("Message", NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty("Stacktrace", NullValueHandling = NullValueHandling.Ignore)]
public string Stacktrace { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty("Data", NullValueHandling = NullValueHandling.Ignore)]
public string Data { get; set; }
}
Then I deserialize it: 然后我反序化它:
const string text = "{\"Code\":-2146232800,\"ExceptionType\":\"IOException\",\"Message\":\"Msg\",\"Stacktrace\":\"Some\"}";
var obj = JsonConvert.DeserializeObject<FileUploadError>(text);
And get subj error. 并得到subj错误。 Reproduced in new console application, which I can provide if required. 在新的控制台应用程序中重现,如果需要,我可以提供。 JSON is very simple, why I am getting this error? JSON很简单,为什么我收到这个错误?
Sample: https://dotnetfiddle.net/76FJd0 示例: https : //dotnetfiddle.net/76FJd0
Stacktrace: 堆栈跟踪:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at FileUploadError..ctor(Exception exception) in d:\Windows\Temp\nclgvim3.0.cs:line 28
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ConstructorInfo constructorInfo, 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.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Program.Main(String[] args)
You need to add a public parameterless constructor to your FileUploadError
class: 您需要向FileUploadError
类添加一个公共无参数构造函数:
public class FileUploadError
{
public FileUploadError()
{
}
Or, you could make it private and use [JsonConstructor]
: 或者,您可以将其[JsonConstructor]
私有并使用[JsonConstructor]
:
public class FileUploadError
{
[JsonConstructor]
private FileUploadError()
{
}
Or, leave it private and deserialize with ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
: 或者,将其保密并使用ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
反序列化:
var settings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
var obj = JsonConvert.DeserializeObject<FileUploadError>(text, settings);
with: 有:
public class FileUploadError
{
private FileUploadError()
{
}
For those tumbling upon this later and since OP's specific case has been solved. 对于那些稍后翻滚的人,以及OP的具体案例已经解决。
Here is what to do to get a clearer error message when it happens. 以下是如何在发生错误消息时获取更清晰的错误消息。
Source: https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm 资料来源: https : //www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm
var errors = new List<string>();
List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(
yourJsonHere,
new JsonSerializerSettings
{
Error = delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
}
});
And errors
will contain a list of the errors that occured! errors
将包含发生的错误列表! Works both for serialization and deserialization ! 适用于序列化和反 序列化 !
Doing so you do lose the context though! 这样做你会失去上下文! So alternatively you can set it to Handled = false
. 因此,您可以将其设置为Handled = false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.