将“[myObject] [1] [application]”字符串转换为JObject上的可用路径

时间:2015-03-19 21:23:26

标签: c# json

首先让我通过使用伪代码向您展示我想要实现的目标。 (是的,我知道这个例子是不可能的)

var path = "[DocInfo][Type]";
var doc = couchDbCall();
var specificProperty = doc[path];

我想在代码中将字符串转换为文字路径访问器,但似乎无法找到任何示例等;可能是由于我缺乏一个好的搜索查询。

{
  "_id": "bb9f9e13-218a-4403-9920-79b0d353634b",
  "_rev": "2-908d1257d7324a8b6f1c333cbefe2e41",
  "Name": "conversionTest2",
  "DocInfo": {
  "Type": "Application",
  "Platform": "test",
  "Version": "12",
  "VersionRelId": -1,
  "Category": "Communications and Messaging",
  "Created": {
  "CreatedDate": "3/19/2015 7:56:07 PM",
  "User": {
    "Id": "bf51f6ce-d3f7-46ff-9ff0-c1e60c2ded44",
    "Name": "Adrian Campos",
    "Email": "adrian.campos@bizdox.com"
  }
},
"Template": "Other Application",
"TemplateVersion": 0
  }
}

1 个答案:

答案 0 :(得分:0)

JSON.Net示例(通过NuGet获取):

dynamic o = JsonConvert.DeserializeObject(yourJsonString);
string type = o.DocInfo.Type; // gets "Application"
var doc = couchDbCall(); 
var specificProperty = doc[type]; // assuming doc takes a string as key

更新:

也有效:

string type = o["DocInfo"]["Type"];

更新2:

据我所知,这个小的递归方法可以帮助你(请注意,没有任何错误处理):

private string DoMyPaths(List<string> paths, JToken token)
{

    string s = paths[0];
    if (paths.Count > 1)
    {
        paths.RemoveAt(0);
        JToken result = token[s];
        return DoMyPaths(paths, result);
    }
    return token[s].ToString();
}

现在你可以传递你的路径(由&#39;。&#39;分隔):

string myPath = "DocInfo.Created.User.Name";
var paths = myPath.Split('.').ToList();
dynamic o = JsonConvert.DeserializeObject(json);
var  result = DoMyPaths(paths, o);

结果:

"Adrian Campos"