解析特定值的未知JSON对象

时间:2014-01-16 17:53:32

标签: c# json json.net

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

假设我的JSON是这样的:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
}

用户会将字符串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]);
}

不幸的是,由于第一个GetValue()返回一个JToken,而不是我希望的另一个JObject,而且我在文档中找不到我可以专门访问特定属性的内容,只是批量JSON。 / p>

或者,在JSON.NET文档中,“查询JSON”示例看起来像是可以解决我的问题,但我不知道如何从字符串表示中生成类似blogPost.Author.Name的内容。

提前感谢您的帮助。

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

3 个答案:

答案 0 :(得分:5)

您可以尝试以下示例:

var jObj = JObject.Parse(jsonString);
var token = jObj.SelectToken(propertyName);

假设jsonString变量是任何json字符串,而propertyName是您想要获得的任何路径。

答案 1 :(得分:1)

IDictionary<string, JToken> Jsondata = JObject.Parse(yourJsonString);
        foreach (KeyValuePair<string, JToken> element in Jsondata) {
            string innerKey = element.Key;
            if (element.Value is JArray) {
                // Process JArray
            }
            else if (element.Value is JObject) { 
                // Process JObject
            }
        }

答案 2 :(得分:0)

这是我用来枚举JSON字符串中的键的一些代码:

private Dictionary<string, object> JSONToDictionary(string jsonString)
{
    var jObj = (JObject)JsonConvert.DeserializeObject(jsonString);
    var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jObj.ToString());

    return dict;
}

然后在你的代码中:

foreach (KeyValuePair<string, object> kvp in JSONToDictionary("{ \"some\": \"jsonfile\" }"))
{
    // (kvp.Key == "some") = true
    // ((kvp.Value as string) == "jsonfile") = true
}
相关问题