【问题标题】:simple JSON helper request - webmatrix/razor简单的 JSON 助手请求 - webmatrix/razor
【发布时间】:2013-03-09 18:24:21
【问题描述】:

我想使用谷歌地图在页面上显示两个地方之间的距离。

所以我知道如何编写 URL,但我不知道如何解码响应并在我的网站上显示?到目前为止,这是我所拥有的:

string distancematrix = "http://maps.googleapis.com/maps/api/distancematrix/json?        origins=34746+Florida&destinations=Universal+Studios+Florida|Orlando+Internation+Airport&mode=driving&units=imperial&sensor=false";
Json.Write(distancematrix, Response.ToString);

我可以使用@命令将每个结果放入页面吗?

谢谢,加文

【问题讨论】:

  • 是的,您可以使用“@”剃刀语法。
  • 另外,如果我正确理解了您的问题,您应该能够只使用“Json.Decode()”来解码 json。你问的是这个吗?
  • 这是到目前为止编写的代码,但它不起作用。我只是希望能够得出一个结果。
  • 'code' string distancematrix = "maps.googleapis.com/maps/api/distancematrix/…"; Json.Write(distancematrix, Response.Output); Json.Decode(distan);
  • 您遇到什么错误?此外,首先,您应该检查以确保您的 JSON 语法正确。您可以在这里快速轻松地做到这一点:jsonlint.com

标签: razor webmatrix json webmatrix-2


【解决方案1】:

这是一个(简化的)示例 cshtml 页面,它从外部文件而不是外部站点获取数据,但它可能对您有所帮助:

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

<html>
    <head>
    </head>
    <body>
        <p>
            @data.destination_addresses <br/>
            @data.origin_addresses <br/>
            @data.rows <br/>
            @data.status
        </p>
    </body>
</html>

我不确定(因为对于以我不习惯看到的方式编写的 JSON 语法,我有点讨厌),但您似乎使用了括号(即“[”和“]” ) 建议使用数组?

如果您以这种方式访问​​数组,它可能看起来像这样:

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

<html>
    <head>
    </head>
    <body>
        <p>
            @{
                while(i < data.destination_addresses.Length)
                {
                    data.destination_addresses[i]; <br/>
                    i++;
                }
            }
        </p>
    </body>
</html>

如果这没有帮助,请告诉我,我们可以从那里开始。

【讨论】:

  • @Gavin5511 您的 JSON 数据路径可能看起来更像这样:var json = File.ReadAllText("http://maps.googleapis.com/maps/api/distancematrix/json? origins=34746+Florida&amp;destinations=Universal+Studios+Florida|Orlando+Internation+Airport&amp;mode=driving&amp;units=imperial&amp;sensor=false") 但无论如何我都不确定,因为我从未尝试过指向 JSON 数据的另一个 url。此外,该方法确实说“File.ReadAllText”,它可能根本不希望有一个完整的外部 url,我不确定......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 2013-11-25
  • 1970-01-01
  • 2012-02-28
  • 2015-12-18
  • 1970-01-01
相关资源
最近更新 更多