```c#
Json数据已生成的C#实体类(其中有int类型和string类型)
namespace WindowsFormsApp2
{
public class Root
{
/// <summary>
///
/// </summary>
public string u { get; set; }
/// <summary>
///
/// </summary>
public string l { get; set; }
/// <summary>
///
/// </summary>
public List<List<int>> n { get; set; }
/// <summary>
///
/// </summary>
public string e { get; set; }
/// <summary>
///
/// </summary>
public int lg { get; set; }
/// <summary>
///
/// </summary>
public int pt { get; set; }
/// <summary>
///
/// </summary>
public string ps { get; set; }
/// <summary>
///
/// </summary>
public string d { get; set; }
}
```
```c#
引用命名空间:
using Newtonsoft.Json;
using System.Net; //HttpWebRequest
using System.IO; //Stream流
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(@"https://phoile.tender88.com/sports-service/sv/odds/events?mk=1&sp=29&ot=2&btg=1&o=1&lg=&ev=&d=&l=100&v=0&me=0&more=false&c=CN&tm=0&g=QQ%3D%3D&pa=0&cl=100&_g=1&pimo=0%2C1%2C8%2C3%2C6%2C7%2C4%2C5&inl=false&_=1671623147061&locale=zh_CN"));
request.Method = "GET"; //请求的方法
request.Accept = "application/json, text/javascript, */*; q=0.01"; //可以接受哪些类型的文件
request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9"); //头部信息添加语言
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"; //访问验证
request.ContentType = "application/json;charset=UTF-8"; //识别编码格式UTF-8
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //响应,强制转换
Stream myResponseStream = response.GetResponseStream(); //获取流,需要引用命名空间IO
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); //流读取器,观察者模式
//textBox1.Text = myStreamReader.ReadToEnd(); //读取放到text里
string getJson = myStreamReader.ReadToEnd();
Root rt = JsonConvert.DeserializeObject<Root>(getJson); //getjson是字符类型,但是Root类里有int和string类型,该如何修改?
MessageBox.Show("A=" + rt.lg + "\r\n" + "B=" + rt.e + "\r\n" + "C=" + rt.ps + "\r\n" + "D=" + rt.pt + "\r\n" + "F=" + rt.l); //这样就可以取出json数据里面的值
for (int i = 0; i < rt.n.Count; i++) //由于这个JSON字符串的 public List<List<int>> n { get; set; }是一个集合,如何把n遍历int类型
{
MessageBox.Show("Data=" + rt.data[i].context + "\r\n" + rt.data[i].location + "\r\n" + rt.data[i].time + "\r\n" + rt.data[i].ftime);
}
myStreamReader.Close(); //关闭
myStreamReader.Dispose(); //释放
myResponseStream.Close(); //关闭流
myResponseStream.Dispose(); //释放流
}
```
Root rt = JsonConvert.DeserializeObject<Root>(getJson); 这行getjson是字符类型,但是Root类里有int和string类型,该如何修改?
for (int i = 0; i < rt.n.Count; i++) //由于这个JSON字符串的 public List<List<int>> n { get; set; } n是一个集合,如何修改遍历
初接触网站接口返回数据给Json解析并显示,以上两行代码小弟不太懂,望大神们指教.
我使用了Newtonsoft.Json,大神们也可以用LitJson.
|