小编dcd*_*oid的帖子

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

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以将"if"语句中的代码块提取到一个单独的方法,例如:

private void ExampleObject GetExampleObject([string of desired type goes here? album/photo/etc])
{
  ExampleObject returnObject = new ExampleObject(); …
Run Code Online (Sandbox Code Playgroud)

.net c# json json.net deserialization

19
推荐指数
2
解决办法
4万
查看次数

标签 统计

.net ×1

c# ×1

deserialization ×1

json ×1

json.net ×1