根据文档的属性对ReadItemAsync()响应进行序列化

huangapple go评论50阅读模式
英文:

Serializing ReadItemAsync() response based on a property of the document

问题

我需要根据存储在Azure Cosmos DB中的文档属性对ReadItemAsync()的响应进行序列化。

所以如果document.type = "dog",我需要序列化为ReadItemAsync<Dog>(),依此类推。

在检索之前,我不知道类型是什么。

有什么好的解决方案吗?

英文:

I need to serialize the response from ReadItemAsync() based on a property of the document stored in Azure Cosmos DB.

So if document.type = &quot;dog&quot;, I need to serialize as ReadItemAsync&lt;Dog&gt;() and so on.

I don't know the type before retrieving it.

What's a good solution for this?

答案1

得分: 1

你可以将其反序列化为 JObject 并在将其映射到特定类之前读取类型属性。

var response = await container.ReadItemAsync&lt;JObject&gt;("myId", new("myPk"));

if (response.Resource.Value&lt;string&gt;("type") == "dog")
{
    var dog = response.Resource.ToObject&lt;Dog&gt;();
}
英文:

You could deserialize it to a JObject and read the type property before mapping it to a specific class.

var response = await container.ReadItemAsync&lt;JObject&gt;(&quot;myId&quot;, new(&quot;myPk&quot;));

if (response.Resource.Value&lt;string&gt;(&quot;type&quot;) == &quot;dog&quot;)
{
    var dog = response.Resource.ToObject&lt;Dog&gt;();
}

huangapple
  • 本文由 发表于 2023年7月7日 04:40:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定