解析特定值的未知JSON对象

Jun*_*ter 2 c# json json.net

我的问题是我试图解析一个未知的json块并查找特定属性的值.我有通往特定属性及其名称的路径,这就是我所知道的.

假设我的JSON是这样的:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
}
Run Code Online (Sandbox Code Playgroud)

用户将传递给我字符串address.city并期望返回字符串New York.但是,请记住,我首先不了解该对象,因此我不能简单地将JSON直接解析为已知的对象容器.

这是我尝试过的,使用JSON.NET.请注意,我没有与此解决方案结合,我只想要一个解决问题的解决方案.

string propertyName = "address.city";
string responseBody= // assume JSON above is here properly formatted
JObject parsedResponseBody = JObject.Parse(responseBody);
string[] parsedPropertyName = propertyName.Split('.');

var foundValue = parsedResponseBody.GetValue(parsedPropertyName[0]);
for (int index = 1; index < parsedPropertyName.Count(); index++)
{
    foundValue = foundValue.getValue(parsedPropertyName[index]);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这分崩离析,因为第一个GetValue()返回一个JToken,而不是我希望的另一个JObject,我在文档中找不到我可以专门访问特定属性,只有批量JSON.

或者,在JSON.NET文档中,"查询JSON"示例看起来像是可以解决我的问题,除了我不知道如何blogPost.Author.Name从其字符串表示生成类似的东西.

在此先感谢您的帮助.

编辑:好的,所以从原始帖子中我不够清楚,从一些答案判断.响应JSON对象不仅未知,而且我不能仅依赖于propertyName字段两个部分.它可以是"prop1.prop2.prop3.prop4",也可以像"prop1"一样简单.

Ili*_*mov 5

您可以尝试以下示例:

var jObj = JObject.Parse(jsonString);
var token = jObj.SelectToken(propertyName);
Run Code Online (Sandbox Code Playgroud)

假设该jsonString变量是任何json字符串,并且propertyName是您想要获得的任何路径.

  • 即使你的`propertyName`类似于`prop1.prop2.prop3.prop41`或只是`prop1`,上面的代码也会有效.只要您知道路径,就可以使用此代码示例获取它. (2认同)