JsonConvert.SerializeObject返回一个空对象
我可以序列化一个通用对象,并且可以在另一个程序集中序列化此对象。我已经验证了这些属性是公共的,并且还用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
}
答案 0 :(得分:0)
在单元测试项目中,我有一个关于Newtonsoft.Json的NuGet参考。我删除了它,对其进行了重建,现在可以使用了。我唯一能想到的是,周围有不同版本的Json(这在我之前发生过),并且正在破坏某些内容。