【问题标题】:fetch country name and region from the url [Google](http://ipinfo.io) [closed]从 url [Google](http://ipinfo.io) [关闭] 获取国家名称和地区
【发布时间】:2015-10-02 05:56:21
【问题描述】:

我有一个返回 json 字符串的 url 结果是:

{
    "ip": "202.141.243.124",
    "hostname": "No Hostname",
    "city": "Peshawar",
    "region": "Khyber Pakhtunkhwa",
    "country": "PK",
    "loc": "34.0080,71.5785",
    "org": "AS9260 Multinet Pakistan Pvt. Ltd.",
    "postal": "24650"
}

我想从中获得国家名称和州名。我怎么才能得到它? 帮帮我,请帮助我完成代码。

【问题讨论】:

标签: c# asp.net json


【解决方案1】:

您需要从 NuGet 安装 Json.Net

PM> Install-Package Newtonsoft.Json

那就试试这个……

void Main()
{
    const string testJson = "{ \"ip\": \"202.141.243.124\", \"hostname\": \"No Hostname\", \"city\": \"Peshawar\", \"region" +
    "\": \"Khyber Pakhtunkhwa\", \"country\": \"PK\", \"loc\": \"34.0080,71.5785\", \"org\": \"AS92" +
    "60 Multinet Pakistan Pvt. Ltd.\", \"postal\": \"24650\" }";
    
    IpInfo ipInfo = JsonConvert.DeserializeObject<IpInfo>(testJson);
    
}


public class IpInfo
{

    [JsonProperty("ip")]
    public string Ip { get; set; }

    [JsonProperty("hostname")]
    public string Hostname { get; set; }

    [JsonProperty("city")]
    public string City { get; set; }

    [JsonProperty("region")]
    public string Region { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("loc")]
    public string Loc { get; set; }

    [JsonProperty("org")]
    public string Org { get; set; }

    [JsonProperty("postal")]
    public string Postal { get; set; }
}

结果


提示

您可以生成复制您尝试反序列化的任何 JSON 文档的结构所需的类,在此示例中,生成的是 IpInfo 类。

您可以通过以下两种方式之一执行此操作,一种是使用 Json2CSharp 并将您的 JSON 数据粘贴到那里以生成类,或者您可以下载 Xamasoft JSON Class Generator(我更喜欢并在回答您的问题时使用的那个) .

【讨论】:

  • 感谢您的回答,但 ip 不会保持不变,它会根据访问我们网站的访问者而改变,所以这段代码可以吗?为此
  • IP不需要保持不变,但是那个JSON文档的结构确实需要保持一致,所以总之,是的,就可以了:)
  • 好的谢谢我应用这个:)
  • 但有一件事我怎么能不上课呢?我想要它动态
  • dynamic ipInfo = JsonConvert.DeserializeObject&lt;dynamic&gt;(testJson); 然后访问IP地址...Console.WriteLine(ipInfo.ip);
【解决方案2】:

您可以使用Json.Net 反序列化为JObject,然后获取regioncountry 值。

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多