[英]JsonConvert.SerializeObject followed by JsonConvert.DeserializeObject throws InvalidCastException
Trying to serialise and deserialise尝试序列化和反序列化
public class DatabaseResponse
{
public string DatabaseName { get; set; }
public string[] Tables { get; set; }
}
Serialise works ok序列化工作正常
DatabaseResponse databaseResponse = new DatabaseResponse
{
DatabaseName = databaseName,
Tables = tableList.ToArray()
};
string response= JsonConvert.SerializeObject(databaseResponse);
but deserialise但反序列化
DatabaseResponse databaseResponse1 = (DatabaseResponse)JsonConvert.DeserializeObject(response);
throws投掷
System.InvalidCastException: 'Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'DatabaseResponse'.'
I have looked at other solutions here but none seem to deal with classes that include both simple properties and array properties我在这里查看了其他解决方案,但似乎没有一个解决包含简单属性和数组属性的类
You don't need to cast it.你不需要投射它。 It is a generic method:
这是一个通用方法:
DatabaseResponse databaseResponse1 = JsonConvert.DeserializeObject<DatabaseResponse>(response);
.DeserializeObject(json)
will return an object
representing the internal classes that JSON.NET uses to represent a JSON document when it doesn't know how you want to represent it. .DeserializeObject(json)
将返回一个object
该object
表示 JSON.NET 用于表示 JSON 文档的内部类,当它不知道您想如何表示它时。
In your specific case, it has represented it as a JObject
, which has no means of being directly cast to a DatabaseResponse
.在您的特定情况下,它已将其表示为
JObject
,它无法直接转换为DatabaseResponse
。 You should instead use the generic .DeserializeObject<T>(json)
, thereby explicitly telling JSON.NET what to deserialize it as:您应该改为使用通用
.DeserializeObject<T>(json)
,从而明确告诉 JSON.NET 将其反序列化为:
DatabaseResponse databaseResponse1 = JsonConvert.DeserializeObject<DatabaseResponse>(response);
DatabaseResponse databaseResponse1 = JsonConvert.DeserializeObject<DatabaseResponse>(response);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.