SerializeObject 正在返回一个空对象

Posted

技术标签:

【中文标题】SerializeObject 正在返回一个空对象【英文标题】:SerializeObject is returning an empty object 【发布时间】:2019-06-11 18:40:25 【问题描述】:

JsonConvert.

我可以序列化一个通用对象,并且我可以在不同的程序集中序列化这个对象。我已经验证了这些属性是公开的,并且还用 json 标记明确标记。 Newtonsoft.Json 没有抛出异常。相关版本 Newtonsoft.Json 12.0.2,通过 nuget 安装。

测试失败,因为预期调用和实际调用不同。实际调用(未粘贴)是我所期望的,但 Json 序列化在测试中给出了一个空对象。

logger.Verify(m => m.LogUsage(JsonConvert.SerializeObject(_svc), "AddService", string.Empty, false), Times.Once());

更新:我尝试添加以下测试,但它仍然序列化为一个空对象,尽管 _svc 被正确定义(我可以通过设置断点并检查它来判断。)

    [TestMethod]
    public async Task TestUnableToSerialize()
    
      string result = JsonConvert.SerializeObject(_svc);

      Assert.AreEqual(string.Empty, result);
    
  [TestClass]
  public class ServiceDirectoryTests
  
    private Service _defaultSvc;
    private ServiceInfoResponse _defaultSvcInfo;
    private Mock<ILogger> logger;
    private ILogger _logger;
    public Service _svc;
    private ServiceInfoResponse _svcInfo;
    private List<string> _serviceMonikers;
    private string _serialized;

    [TestInitialize()]
    public void Initialize()
    
      logger = new Mock<ILogger>();
      _logger = logger.Object;

      _defaultSvcInfo = new ServiceInfoResponse()
      
        endpoint = "default endpoint",
        environment_id = string.Empty,
        id = "defaultId",
        iso_a2_country_code = "UK",
        moniker = "Account",
        tenant_moniker = "default",
        url_selection_scheme = UrlSelectionScheme.ServiceDefault
      ;

      _defaultSvc = new Service(_defaultSvcInfo);

      _svcInfo = new ServiceInfoResponse()
      
        endpoint = "service endpoint",
        environment_id = string.Empty,
        id = "nonDefaultId",
        iso_a2_country_code = "UK",
        moniker = "Account",
        tenant_moniker = "ztorstrick",
        url_selection_scheme = UrlSelectionScheme.ServiceDefault
      ;

      _svc = new Service(_svcInfo);
    

    [TestMethod]
    public async Task AddServiceDefaultReturned()
    
      Mock<IServiceDirectory> mockClient = new Mock<IServiceDirectory>();
      mockClient.Setup(x => x.CreateService(
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<string>()
      ))
      .ReturnsAsync(_defaultSvcInfo);

      ServiceDirectory svc = new ServiceDirectory(mockClient.Object, _logger);

      Service result = await svc.AddService(_svc, "");
      Assert.AreEqual(_defaultSvc.Endpoint, result.Default);
      Assert.AreEqual(result.Default, result.Endpoint);
      Assert.AreEqual(_defaultSvc.EnvironmentId, result.EnvironmentId);
      Assert.AreEqual(string.Empty, result.Id);
      Assert.AreEqual(_defaultSvc.IsoA2CountryCode, result.IsoA2CountryCode);
      Assert.AreEqual(_defaultSvc.Moniker, result.Moniker);
      Assert.AreEqual(_defaultSvc.ServiceName, result.ServiceName);
      Assert.AreEqual(_defaultSvc.TenantMoniker, result.TenantMoniker);
      Assert.AreEqual("ServiceDefault", result.UrlSelectionScheme);

      logger.Verify(m => m.LogUsage(JsonConvert.SerializeObject(_svc), "AddService", string.Empty, false), Times.Once());
    
  

  public class Service : PropertyChangedBase
  
    #region " Private Variables "

    private string _default;
    private string _endpoint;
    private string _environmentId;
    private string _id;
    private bool _isSelected;
    private string _isoA2CountryCode;
    private string _moniker;
    private string _serviceName;
    private string _tenantMoniker;
    private string _urlSelectionScheme;
    private string _version;

    #endregion

    #region "Constructors"

    public Service()
    
      Id         = string.Empty;
      IsDirty    = false;
      IsSelected = false;
    

    public Service(Service service)
    
      if (service == null)  throw new ArgumentNullException(); 

      Default            = service.Default;
      Endpoint           = service.Endpoint;
      EnvironmentId      = service.EnvironmentId;
      Id                 = service.Id;
      IsDirty            = service.IsDirty;
      IsoA2CountryCode   = service.IsoA2CountryCode;
      IsSelected         = service.IsSelected;
      Moniker            = service.Moniker;
      ServiceName        = service.ServiceName;
      TenantMoniker      = service.TenantMoniker;
      UrlSelectionScheme = service.UrlSelectionScheme;

      // DO NOT keep Ids for default services, to prevent accidental editing and deletion
      if (string.IsNullOrWhiteSpace(service.TenantMoniker) ||
         string.Equals(service.TenantMoniker, "default", StringComparison.CurrentCultureIgnoreCase))
      
        Id = string.Empty;
      
    

    public Service(ServiceInfoResponse response)
    
      if (response == null)  throw new ArgumentNullException(); 

      IsDirty            = false;
      Endpoint           = response.endpoint;
      EnvironmentId      = response.environment_id;
      Id                 = response.id;
      IsoA2CountryCode   = response.iso_a2_country_code;
      IsSelected         = false;
      Moniker            = response.moniker;
      ServiceName        = response.service_name;
      TenantMoniker      = response.tenant_moniker;
      UrlSelectionScheme = response.url_selection_scheme.ToString();

      // DO NOT keep Ids for default services, to prevent accidental editing and deletion
      if(string.IsNullOrWhiteSpace(response.tenant_moniker) || 
         string.Equals(response.tenant_moniker, "default", StringComparison.CurrentCultureIgnoreCase))
      
        Id = string.Empty;
      
    

    #endregion

    #region "Properties"

    [JsonIgnore]
    public string Default
    
      get  return _default; 

      set
      
        if (_default != value)
        
          _default = value;
          NotifyOfPropertyChange(() => Default);
        
      
    

    [JsonProperty("endpoint")]
    public string Endpoint
    
      get  return _endpoint; 

      set
      
        if (_endpoint != value)
        
          _endpoint = value;
          NotifyOfPropertyChange(() => Endpoint);
        
      
    

    [JsonProperty("environment_id")]
    public string EnvironmentId
    
      get  return _environmentId; 

      set
      
        if (_environmentId != value)
        
          _environmentId = value;
          NotifyOfPropertyChange(() => EnvironmentId);
        
      
    

    [JsonProperty("id")]
    public string Id
    
      get  return _id; 

      set
      
        if (_id != value)
        
          _id = value;
          NotifyOfPropertyChange(() => Id);
          NotifyOfPropertyChange(() => IsDefault);
        
      
    

    [JsonIgnore]
    public bool IsDefault
    
      get
      
        return string.IsNullOrWhiteSpace(Id);
      
    

    [JsonIgnore]
    public bool IsDirty  get; set; 

    public bool IsSelected
    
      get  return _isSelected; 

      set
      
        if (_isSelected != value)
        
          _isSelected = value;
          NotifyOfPropertyChange(() => IsSelected);
        
      
    

    [JsonProperty("iso_a2_country_code")]
    public string IsoA2CountryCode
    
      get  return _isoA2CountryCode; 

      set
      
        if (_isoA2CountryCode != value)
        
          _isoA2CountryCode = value;
          NotifyOfPropertyChange(() => IsoA2CountryCode);
        
      
    

    [JsonIgnore]
    public bool MatchesDefault  get  return string.Equals(Endpoint, Default, StringComparison.CurrentCultureIgnoreCase);  

    [JsonProperty("moniker")]
    public string Moniker
    
      get  return _moniker; 

      set
      
        if (_moniker != value)
        
          _moniker = value;
          NotifyOfPropertyChange(() => Moniker);
        
      
    

    [JsonProperty("service_name")]
    public string ServiceName
    
      get  return _serviceName; 

      set
      
        if (_serviceName != value)
        
          _serviceName = value;
          NotifyOfPropertyChange(() => ServiceName);
        
      
    

    [JsonProperty("tenant_moniker")]
    public string TenantMoniker
    
      get  return _tenantMoniker; 

      set
      
        if (_tenantMoniker != value)
        
          _tenantMoniker = value;
          NotifyOfPropertyChange(() => TenantMoniker);
        
      
    

    [JsonProperty("url_selection_scheme")]
    public string UrlSelectionScheme
    
      get  return _urlSelectionScheme; 

      set
      
        if (_urlSelectionScheme != value)
        
          _urlSelectionScheme = value;
          NotifyOfPropertyChange(() => UrlSelectionScheme);
        
      
    

    [JsonProperty("version")]
    public string Version
    
      get  return _version; 

      set
      
        if (_version != value)
        
          _version = value;
          NotifyOfPropertyChange(() => Version);
        
      
    

    #endregion
  

【问题讨论】:

你能分享一个minimal reproducible example吗?你没有使用xamarin-live-player 是吗? 我不知道 xamarin-live-player 是什么,但我怀疑我正在使用它。这是一个 wpf 项目并使用了我无法共享的专有库,因此可重现的示例是一个问题。我试图分享所有相关的内容。 我试图创建一个仅包含相关部分的控制台项目,但我无法以这种方式重现它。我会继续尝试找出破坏它的原因,但希望有人能指出我正在做的一些愚蠢的事情。 【参考方案1】:

我的单元测试项目中有一个对 Newtonsoft.Json 的 NuGet 引用。我删除了它,重建了它,现在它可以工作了。我能想到的唯一一件事是有不同版本的 Json 浮动(这曾经发生在我身上)并且它正在破坏某些东西。

【讨论】:

以上是关于SerializeObject 正在返回一个空对象的主要内容,如果未能解决你的问题,请参考以下文章

JsonConvert.SerializeObject 在 Xamarin 表单中始终返回

我的 ObjectType 正在返回一个空对象 [重复]

getStaticProps 返回一个空对象

JsonConvert.SerializeObject 更改 JSON 中字段的排序顺序

findOne 返回一个空对象

为啥 TypeError 上的 JSON.stringify 返回一个空对象 [重复]