c# - 如何以编程方式从动态 JObject 获取属性

标签 c# .net json json.net deserialization

我正在使用 NewtonSoft JObject 解析 JSON 字符串。 如何以编程方式从动态对象获取值? 我想简化代码,不要为每个对象重复自己。

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”语句中的代码块提取到单独的方法中,例如:

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?

谢谢。

最佳答案

假设您使用的是 Newtonsoft.Json.Linq.JObject,则无需使用动态。 JObject 类可以采用字符串索引器,就像字典一样:

JObject myResult = GetMyResult();
returnObject.Id = myResult["string here"]["id"];

希望这对您有所帮助!

关于c# - 如何以编程方式从动态 JObject 获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16097768/

相关文章:

c# - 如何将调试文本从 C# 类发送到 ASP.NET 页面

c# - 对于简单情况何时使用 MessageQueueTransaction?

c# - 访问内部 API Controller

c# - 使用 Adaptive Cards Designer,然后用 C# 中的真实值替换示例值

c# - 循环收集以找到最小值

java - jackson 的嵌套映射

xml - 描述 REST 服务

android - 在 ListView 中加载更多的 json 数据

c# - 使用 AttributeTargets.Class 对自定义 ValidationAttribute 进行客户端验证

.net - 无法安装 .NET Standard 2.0