【问题标题】:Deserialize json with missing default constructor in the class in C# using JSON.NET使用 JSON.NET 反序列化 C# 类中缺少默认构造函数的 json
【发布时间】:2020-03-19 16:53:35
【问题描述】:

我正在尝试将deserialize 一个字符串转换为一个对象。问题是我想使用默认构造函数反序列化,但该类中不存在。该类只有一个带参数的构造函数。而且我不允许换班。我的场景是这样的:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class ConnectionSummary
{   
    public ConnectionSummary(Connection connection)
    {
        this.ConnectionId = connection.Id;
        this.SystemId = connection.SystemId;
    }

    [JsonProperty(PropertyName = "connectionId", Required = Required.Always)]
    public string ConnectionId { get; set; }

    [JsonProperty(PropertyName = "systemId")]
    public string SystemId { get; set; }
}


public class Connection
{
    public Connection()
    {
        // Initialization of some properties
    }

    [JsonProperty(PropertyName = "systemId", Required = Required.Always)]
    public string SystemId { get; set; }

    [JsonProperty(PropertyName = "id", Required = Required.Always)]
    public string Id { get; set; }

    // Other properties
}


public class Program
{
    public static void Main()
    {
        var json = "{\"connectionId\":\"id\",\"systemId\":\"sId\"}";
        var deserial = JsonConvert.DeserializeObject<ConnectionSummary>(json); // getting error here.
        Console.WriteLine(deserial.ToString());
    }
}

堆栈跟踪:

Run-time exception (line 43): Exception has been thrown by the target of an invocation.

Stack Trace:

[System.NullReferenceException: Object reference not set to an instance of an object.]
   at ConnectionSummary..ctor(Connection connection) :line 9

[System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.]
   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 Newtonsoft.Json.Utilities.LateBoundReflectionDelegateFactory.<>c__DisplayClass3_0.<CreateParameterizedConstructor>b__0(Object[] a)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor`1 creator, String id)
   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.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() :line 43

我发现如果我在ConnectionSummary 类中添加private 默认构造函数并在JsonSerializerSettings 中添加ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,可以解决问题,但我不能这样做。我在这里还有什么可以做的吗? Fiddle Url

【问题讨论】:

  • 你为什么反序列化到ConnectionSummary,而你应该只使用Connection
  • 对不起,我应该解释一下。 ConnectionSummary 也有其他属性。
  • 要在这里给出正确答案,上下文很重要。您的流程的哪一部分应该调用“反序列化”?
  • 但是您的 JSON 与您的对象不匹配。您在这里向我们展示了子对象,Newtonsoft 不知道如何制作 Connection 对象,除非您编写自定义转换器。
  • 上下文是这样的:Web API 返回Task&lt;ConnectionSummary&gt;。我正在编写测试。我需要调用这个 API,然后反序列化 response.Content,然后做进一步的检查。

标签: c# json json.net json-deserialization


【解决方案1】:

您可以通过为ConnectionSummary 类创建自定义JsonConverter 来解决此问题,如下所示:

public class ConnectionSummaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ConnectionSummary);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        Connection conn = new Connection
        {
            Id = (string)jo["connectionId"],
            SystemId = (string)jo["systemId"]
        };
        return new ConnectionSummary(conn);
    }

    public override bool CanWrite 
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

然后像这样反序列化:

var deserial = JsonConvert.DeserializeObject<ConnectionSummary>(json, new ConnectionSummaryConverter());

小提琴:https://dotnetfiddle.net/U4UR3o

【讨论】:

    【解决方案2】:

    在这种情况下,您可以自己调用构造函数,并将实例提供给转换器:

    var json = "{\"connectionId\":\"id\",\"systemId\":\"sId\"}";
    var cs = new ConnectionSummary(new Connection());
    Newtonsoft.Json.JsonConvert.PopulateObject(json, cs);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多