gpt4 book ai didi

c# - 使用 C# 从 json 数据中获取值

转载 作者:太空宇宙 更新时间:2023-11-03 10:27:16 24 4
gpt4 key购买 nike

我正在使用 C# 创建一个 Windows 窗体应用程序项目

我想在我的文本框中显示与 IP 地址相关的所有信息(如不同标签中的城市名称、国家/地区代码等)。我已经阅读了很多关于 JsonConvert 的文章,但我不想使用 JsonConvert

这是我的 C# 代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace GetIPinfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
List<LocaionInfo1> locations = new List<LocaionInfo1>();
string url = string.Format("http://ipinfo.io/" + txtip.Text);
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
LocaionInfo1 location = new JavaScriptSerializer().Deserialize<LocaionInfo1>(json);
locations.Add(location);
}

if (locations.Count > 0)
{
foreach (LocaionInfo1 loc in locations)
{
label9.Text = loc.CityName;
label10.Text = loc.CountryCode;
label11.Text = loc.CountryName;
}
}
}

public class LocaionInfo1
{
public string IPAddress { get; set; }
public string CountryName { get; set; }
public string CountryCode { get; set; }
public string CityName { get; set; }
public string RegionName { get; set; }
public string ZipCode { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string TimeZone { get; set; }
}
}
}

问题是,当我调试此代码并在我的文本框中输入 IP,然后单击提交按钮时我的 LocaionInfo1 location = new JavaScriptSerializer().Deserialize<LocaionInfo1>(json);NULL 值。

JSON 数据是:

{
"ip": "182.69.151.41",
"hostname": "abts-north-dynamic-041.151.69.182.airtelbroadband.in",
"city": null,
"country": "IN",
"loc": "20.0000,77.0000",
"org": "AS24560 Bharti Airtel Ltd., Telemedia Services"
}

所以请帮助获取这些所有值。我正在使用 Visual Studio 2012。

最佳答案

所以我实际上不能尝试这个,因为我在移动设备上,但对于实际的 JSON,您必须向链接添加“/json”

string url = string.Format("http://ipinfo.io/" + txtip.Text + "/json");

关于c# - 使用 C# 从 json 数据中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31292525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com