簡體   English   中英

Newtonsoft json.net反序列化NullReferenceException

[英]Newtonsoft json.net deserialization NullReferenceException

我有一個使用WCF Rest客戶端生成的簡單JSON,但是當我嘗試反序列化響應時,我在JSON.Net中收到錯誤NullReferenceException 我有以下JSON:

{"Code":-2146232800,"ExceptionType":"IOException","Message":"Msg","Stacktrace":"Some"}

下課:

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

然后我反序化它:

const string text = "{\"Code\":-2146232800,\"ExceptionType\":\"IOException\",\"Message\":\"Msg\",\"Stacktrace\":\"Some\"}";
var obj = JsonConvert.DeserializeObject<FileUploadError>(text);

並得到subj錯誤。 在新的控制台應用程序中重現,如果需要,我可以提供。 JSON很簡單,為什么我收到這個錯誤?

示例: https//dotnetfiddle.net/76FJd0

堆棧跟蹤:

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)

您需要向FileUploadError類添加一個公共無參數構造函數:

public class FileUploadError
{
    public FileUploadError()
    {
    }

或者,您可以將其[JsonConstructor]私有並使用[JsonConstructor]

public class FileUploadError
{
    [JsonConstructor]
    private FileUploadError()
    {
    }

或者,將其保密並使用ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor反序列化:

var settings = new JsonSerializerSettings
{
    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
var obj = JsonConvert.DeserializeObject<FileUploadError>(text, settings);

有:

public class FileUploadError
{
    private FileUploadError()
    {
    }

對於那些稍后翻滾的人,以及OP的具體案例已經解決。

以下是如何在發生錯誤消息時獲取更清晰的錯誤消息。

資料來源: 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;
        }
    });

errors將包含發生的錯誤列表! 適用於序列化 序列化

這樣做你會失去上下文! 因此,您可以將其設置為Handled = false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM