解析JTokens以提取值

时间:2017-02-07 01:58:27

标签: c# json

我在C#中将JSON对象作为字符串。我可以将其解析为JObject。像这样:

JObject resultObject = JObject.Parse(responseText);

resultObject的值如下所示:

"mappings": {
    "car": {
        "properties": {
            "manufacturer": {
                "type": "text",
                {...}
            },
            "model": {
                "type": "text",
                {...}
            },
            "production": {
                "type": "date",
                 {...}
            }
        }
    }
}

我想以某种方式映射它:

class MyProperty {
   string Name { get; set;}
   string Type { get; set;}
}   

是否有方便的方法迭代所有找到的属性,将名称和类型提取到像MyProperty这样的简单类中?

修改

这是我到目前为止所提出的:

请帮助我找到更好,更优雅的方式!

string type = "car"

JObject properties = resultObject["mappings"][type]["properties"].Value<JObject>();
List<string> keys = properties.Properties().Select(p => p.Name).ToList();
// keys: ["manufacturer", "model", "production"]

foreach (string key in keys) {
    string currType = properties[key]["type"].Value<string>();

    MyProperty mypropObject = new MyProperty(){ Name = key, Type = currType };
}

0 个答案:

没有答案