从json对象数组中获取WebMatrix C#对象数组

时间:2013-02-13 17:23:01

标签: c# arrays json object webmatrix

鉴于json文件(json对象)看起来像这样(一个对象数组):

{
    "job": [
        {
            "title": "Mechanic",
            "department": "Central Repair Department",
            "summary": "Repair and perform preventative maintenance to vehicles and equipment.",
            "qualifications": "High school diploma or equivalent, valid Oklahoma driver's license, general knowledge of operating principals of gasoline and diesel engines, and experience with mechanical repair of vehicles. Basic knowledge of hydraulics and equipment is also desirable.",
            "incentive": "",
            "wage": ""
        },
        {
            "title": "Police Patrol Officer",
            "department": "Police Department",
            "summary": "Repair and perform preventative maintenance to vehicles and equipment.",
            "qualifications": "High school diploma or equivalent, valid Oklahoma driver's license, general knowledge of operating principals of gasoline and diesel engines, and experience with mechanical repair of vehicles. Basic knowledge of hydraulics and equipment is also desirable.",
            "incentive": "",
            "wage": ""
        }
    ]
}

如何获得用这些值绘制的对象数组?

如果您熟悉如何在WebMatrix的C#中执行此操作,请回答(这与常规C#不同,即没有JsonReader方法,没有JObject方法,也没有其他C#建议指示的其他方法)。虽然,我认为它是'可能的',我无法找到正确的使用指令用于其中一些方法,但WebMatrix的细微差别再次让我无法找到这些信息,如果它确实在那里。

此外,我不知道LINQ是什么或如何使用它,我也不关心,除非它绝对是最好/最简单的方式。

我在WebMatrix中注意到的与json有关的一些非静态方法包括'DynamicJsonObject'和'DynamicJsonArray',但是,是否路径到文件[使用Server.MapPath或不使用]或只是给它完整的json文件存储为单个字符串变量,我尝试使用这些方法的任何内容都没有成功。

没有简单的方法可以从json对象数组中简单地创建一个C#对象数组吗?

感谢您的帮助!如果您需要任何进一步的信息,请告诉我。

1 个答案:

答案 0 :(得分:1)

您可以使用Json Helper将JSON解码为动态对象。假设您在上面发布的JSON位于名为JsonFile.txt的文件中,以下内容将执行此操作:

@{
    var json = File.ReadAllText(Server.MapPath("~/JsonFile.txt"));
    var data = Json.Decode(json);
}

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @foreach(var j in data.job){
            <h3>@j.title</h3>
            <div>@j.summary</div>
        }
    </body>
</html>