将 JSON 对象反序列化为 System.Guid 类型



我有一个JSON格式的REST响应,看起来像这样:{ "guid": "c75d06a8-a705-48ec-b6b3-9076becf20f4" }

当尝试将此响应字符串反序列化为System.Guid类型的对象时,如下所示:Newtonsoft.Json.JsonConvert.DeserializeObject(response.content, type);,抛出以下异常:

无法将当前 JSON 对象(例如

{"name":"value"}(反序列化为类型"System.Nullable'1[System.Guid]",因为该类型需要 JSON 原语值(例如字符串、数字、布尔值、null(才能正确反序列化。 若要修复此错误,请将 JSON 更改为 JSON 基元值(例如字符串、数字、布尔值、null(,或者更改反序列化类型,使其是可以从 JSON 对象反序列化的普通 .NET 类型(例如,不是整数等基元类型,也不是数组或列表等集合类型(。还可以将 JsonObjectAttribute 添加到类型中,以强制它从 JSON 对象反序列化。 路径"指导",第 1 行,位置 8。

任何帮助不胜感激!

如果不想创建仅包含 Guid 值的类,可以直接从解析的 JSON 中解析该值:

string json = "{ "guid": "c75d06a8-a705-48ec-b6b3-9076becf20f4" }";
var container = JToken.Parse(json);
Guid guid;
if (Guid.TryParse(container["guid"]?.ToString(), out guid))
{
Console.WriteLine(guid);    
}
else{
Console.WriteLine("No guid present or it has an invalid format");
}
// c75d06a8-a705-48ec-b6b3-9076becf20f4

另一种选择是使用动态变量,尽管我个人认为这不是动态的良好用例:

string json = "{ "guid": "c75d06a8-a705-48ec-b6b3-9076becf20f4" }";
dynamic container = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
Guid guid;
if (Guid.TryParse(container.guid?.ToString(), out guid)) {
Console.WriteLine(guid);
}
else {
Console.WriteLine("No guid present or it has an invalid format");
}
// c75d06a8-a705-48ec-b6b3-9076becf20f4

自从我做过这种事情以来已经有一段时间了,但是我认为答案在您的错误消息中。 让它像字符串一样回来。 在类中重写 guid 字符串属性以设置 GUID 类型的另一个属性,并在其中执行转换和错误处理。 另一种方法是使用构造函数来提供帮助。 希望这能给你一个方向。

GUID 和 Json 的完整示例

string content = "{"data":{"Type":"Foo","Description":"bar ","Software":"baz","Version":"qux","Url":"http://example.com","DatabasePortNumber":1,"Id":"2cdc66f1-0000-0000-39ac-233c00000000"}}";
var result_SystemText = System.Text.Json.JsonSerializer.Deserialize<SystemApplicationResponse>(content);  //Will result in null-object
var result_Newtonsoft = Newtonsoft.Json.JsonConvert.DeserializeObject<SystemApplicationResponse>(content); //Will result in correctly serialized object
public class SystemApplicationResponse
{
public SystemApplicationDto Data { get; set; }
}

public class SystemApplicationDto
{
public SystemApplicationDtoType Type { get; set; }
public string Description { get; set; }
public string Software { get; set; }
public string Version { get; set; }
public string Url { get; set; }
public int DatabasePortNumber { get; set; }
public System.Guid Id { get; set; }
}
public enum SystemApplicationDtoType
{
Foo = 0
}

相关内容

最新更新