How to get property from dynamic JObject programmatically(如何以编程方式从动态 JObject 获取属性)
问题描述
我正在使用 NewtonSoft JObject 解析 JSON 字符串.如何以编程方式从动态对象中获取值?我想简化代码,不要为每个对象重复自己.
I'm parsing a JSON string using the NewtonSoft JObject. How can I get values from a dynamic object programmatically? I want to simplify the code to not repeat myself for every object.
public ExampleObject GetExampleObject(string jsonString)
{
ExampleObject returnObject = new ExampleObject();
dynamic dynamicResult = JObject.Parse(jsonString);
if (!ReferenceEquals(dynamicResult.album, null))
{
//code block to extract to another method if possible
returnObject.Id = dynamicResult.album.id;
returnObject.Name = dynamicResult.album.name;
returnObject.Description = dynamicResult.albumsdescription;
//etc..
}
else if(!ReferenceEquals(dynamicResult.photo, null))
{
//duplicated here
returnObject.Id = dynamicResult.photo.id;
returnObject.Name = dynamicResult.photo.name;
returnObject.Description = dynamicResult.photo.description;
//etc..
}
else if..
//etc..
return returnObject;
}
有什么方法可以将if"语句中的代码块提取到单独的方法中,例如:
Is there any way I can extract the code blocks in the "if" statements to a separate method e.g:
private void ExampleObject GetExampleObject([string of desired type goes here? album/photo/etc])
{
ExampleObject returnObject = new ExampleObject();
returnObject.Id = dynamicResult.[something goes here?].id;
returnObject.Name = dynamicResult.[something goes here?].name;
//etc..
return returnObject;
}
是否有可能,因为我们不能对动态对象使用反射.或者我是否正确使用了 JObject?
Is it even possible since we can't use reflection for dynamic objects. Or am I even using the JObject correctly?
谢谢.
推荐答案
假设您使用的是 Newtonsoft.Json.Linq.JObject,则不需要使用动态.JObject 类可以采用字符串索引器,就像字典一样:
Assuming you're using the Newtonsoft.Json.Linq.JObject, you don't need to use dynamic. The JObject class can take a string indexer, just like a dictionary:
JObject myResult = GetMyResult();
returnObject.Id = myResult["string here"]["id"];
希望这会有所帮助!
这篇关于如何以编程方式从动态 JObject 获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何以编程方式从动态 JObject 获取属性
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01