我正在使用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"];
希望这可以帮助!