Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过foreach循环使用httpClient.sendaync(请求)解析JSON_C# - Fatal编程技术网

C# 通过foreach循环使用httpClient.sendaync(请求)解析JSON

C# 通过foreach循环使用httpClient.sendaync(请求)解析JSON,c#,C#,我正在使用NewtonSoft解析JSON Api调用 代码的格式必须保持不变 我唯一的问题是我不能在foreach循环中迭代JSON的值 我怎样才能解决这个问题 public异步任务callWebApi() { 使用(var httpClient=new httpClient()) { 使用(var request=newhttprequestmessage(newhttpmethod(“GET”),”https://www.metaweather.com/api/location/sear

我正在使用NewtonSoft解析JSON Api调用

代码的格式必须保持不变

我唯一的问题是我不能在foreach循环中迭代JSON的值

我怎样才能解决这个问题

public异步任务callWebApi()
{
使用(var httpClient=new httpClient())
{
使用(var request=newhttprequestmessage(newhttpmethod(“GET”),”https://www.metaweather.com/api/location/search/?lattlong=50.068,-5.316"))
{
var response=wait httpClient.sendaync(请求);
使用(HttpContent=response.content)
{
var jsonString=await response.Content.ReadAsStringAsync();
var data=JsonConvert.DeserializeObject(jsonString);
WriteLine(“我需要解析距离、标题、位置类型、woeid、latt_long,以便使用foreach循环遍历它”);
控制台写入线(数据);
Console.Read();
//我不知道如何获取json的值
}
}
}

首先,我认为使用您正在使用的代码与其他站点建立外部链接不是一个好主意。

话虽如此,您需要首先知道json是什么,然后为它创建一个合适的类,在您的情况下,json如下所示

[{“距离”:16744,标题:““彭赞斯”,“地点类型”:“城市”,“沃伊德”:31889,“拉图隆”:“50.11861,-5.53723”},{“距离”:19287,标题:““法尔茅斯”,“地点类型”:“城市”,“沃伊德”:19894,“拉图隆”:“50.151001,-5.07832”},{“距离”:19904,标题:““圣”
艾夫斯,“地点类型”:“城市”、“沃伊德”:35662,“拉特朗”:“50.21032,-5.48569”},{“距离”:28619,“标题”:“特鲁罗”,“地点类型”:“城市”、“沃伊德”:38283,“拉特朗”:“50.263691,-5.054610”},{“距离”:90542,“位置类型”:“城市”、“沃伊德”:32185,“拉特朗”:“50.375801,-4.890”{“距离”:146738,“位置类型”:“埃克塞特”,“位置类型”:“城市”,Weeid:19792,“latt_long”:“50.720760,-3.515340”},{“距离”:162575,“位置类型”:“城市”,“Weeid”:34811,“latt_long”:“50.687439,-3.23757”},{“距离”:197916,“斯旺西”,“位置类型”:“城市”,“Weeid”:36758,“latt_long”:“51.623150,-3.940930”},{“距离”:21789,“标题”:“卡迪夫”,“位置类型”:“城市”,“Weeid”:,“拉图隆”:“51.481251,-3.180730”},{“距离”:245712,“标题”:“布里斯托尔”,“地点类型”:“城市”,“世界”:13963,“拉图隆”:“51.453732,-2.591560”}]

这个班看起来像这样

public class WeatherClass
{
    public int distance { get; set; }
    public string title { get; set; }
    public string location_type { get; set; }
    public int woeid { get; set; }
    public string latt_long { get; set; }
}
一旦你有了它,因为你的响应是一个,当我们使用json时,我们需要告诉它它是一个数组,这样它就知道它一次可以预期多个对象项

因此,需要这样的东西来反序列化响应内容数据

List<WeatherClass> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeatherClass>>(jsonString);
这是您的代码和我的更改

public class WeatherClass
{
    public int distance { get; set; }
    public string title { get; set; }
    public string location_type { get; set; }
    public int woeid { get; set; }
    public string latt_long { get; set; }
}

public async Task callWebApi()
{
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://www.metaweather.com/api/location/search/?lattlong=50.068,-5.316"))
        {
            var response = await httpClient.SendAsync(request);
            using (HttpContent content = response.Content)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                List<WeatherClass> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeatherClass>>(jsonString);

                foreach (var weatherItem in data)
                {
                    Console.WriteLine(weatherItem.distance);
                    Console.WriteLine(weatherItem.latt_long);
                    Console.WriteLine(weatherItem.location_type);
                    Console.WriteLine(weatherItem.title);
                    Console.WriteLine(weatherItem.woeid);
                }
            }
        }
    }
}

static void Main()
{
    Program P1 = new Program();

    try
    {
        P1.callWebApi().Wait();

    }
    catch (Exception ex)
    {
        Console.WriteLine("There was an exception, {0}", ex.ToString());
        Console.Read();
    }
}
公共类天气类
{
公共整数距离{get;set;}
公共字符串标题{get;set;}
公共字符串位置\u类型{get;set;}
public int woeid{get;set;}
公共字符串latt_long{get;set;}
}
公共异步任务callWebApi()
{
使用(var httpClient=new httpClient())
{
使用(var request=newhttprequestmessage(newhttpmethod(“GET”),”https://www.metaweather.com/api/location/search/?lattlong=50.068,-5.316"))
{
var response=wait httpClient.sendaync(请求);
使用(HttpContent=response.content)
{
var jsonString=await response.Content.ReadAsStringAsync();
List data=Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
foreach(数据中的var weatherItem)
{
控制台写入线(weatherItem.距离);
控制台写入线(weatherItem.latt_long);
控制台写入线(weatherItem.location\u类型);
控制台写入线(weatherItem.title);
控制台写入线(weatherItem.woeid);
}
}
}
}
}
静态void Main()
{
程序P1=新程序();
尝试
{
P1.callWebApi().Wait();
}
捕获(例外情况除外)
{
WriteLine(“有一个异常,{0}”,例如ToString());
Console.Read();
}
}

您只需要两行代码

1) 将json解析为
JToken

2) 将解析的
JToken
转换为
JObject
数组,从每个
JObject
中,您可以通过其键名访问每个属性

...

using (HttpContent content = response.Content)
{
    var jsonString = await response.Content.ReadAsStringAsync();

    //1
    JToken jToken = JToken.Parse(jsonString);

    //2
    JObject[] items = jToken.ToObject<JObject[]>();

    foreach (var item in items)
    {
        Console.WriteLine(item["distance"]);
        Console.WriteLine(item["latt_long"]);
        Console.WriteLine(item["location_type"]);
        Console.WriteLine(item["title"]);
        Console.WriteLine(item["woeid"]);
        Console.WriteLine();
    }

    Console.Read();
}
。。。
使用(HttpContent=response.content)
{
var jsonString=await response.Content.ReadAsStringAsync();
//1
JToken JToken=JToken.Parse(jsonString);
//2
JObject[]items=jToken.ToObject();
foreach(项目中的var项目)
{
控制台写入线(项目[“距离]);
控制台写入线(项目[“latt_long”);
控制台写入线(项目[“位置类型]);
Console.WriteLine(项目[“标题]);
控制台写入线(项目[“woeid”);
Console.WriteLine();
}
Console.Read();
}
输出:


这不起作用。我收到以下错误:无法将当前json对象反序列化,因为(例如,{“name”:“value”})需要json数组(例如[1,2,3])才能转换为类型要正确反序列化。对我来说有效,您提到的错误是因为json是数组,您需要将其反序列化为数组对象。这不起作用。我收到以下错误:无法反序列化当前json对象,因为(例如,{“name”:“value”})是类型,因为该类型需要json数组(例如[1,2,3])要正确反序列化。您是否使用了您在问题中提到的相同url?因为我使用了相同的url,您可以看到上面的输出屏幕截图。我只需复制上面的代码并查看
public class WeatherClass
{
    public int distance { get; set; }
    public string title { get; set; }
    public string location_type { get; set; }
    public int woeid { get; set; }
    public string latt_long { get; set; }
}

public async Task callWebApi()
{
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://www.metaweather.com/api/location/search/?lattlong=50.068,-5.316"))
        {
            var response = await httpClient.SendAsync(request);
            using (HttpContent content = response.Content)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                List<WeatherClass> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeatherClass>>(jsonString);

                foreach (var weatherItem in data)
                {
                    Console.WriteLine(weatherItem.distance);
                    Console.WriteLine(weatherItem.latt_long);
                    Console.WriteLine(weatherItem.location_type);
                    Console.WriteLine(weatherItem.title);
                    Console.WriteLine(weatherItem.woeid);
                }
            }
        }
    }
}

static void Main()
{
    Program P1 = new Program();

    try
    {
        P1.callWebApi().Wait();

    }
    catch (Exception ex)
    {
        Console.WriteLine("There was an exception, {0}", ex.ToString());
        Console.Read();
    }
}
...

using (HttpContent content = response.Content)
{
    var jsonString = await response.Content.ReadAsStringAsync();

    //1
    JToken jToken = JToken.Parse(jsonString);

    //2
    JObject[] items = jToken.ToObject<JObject[]>();

    foreach (var item in items)
    {
        Console.WriteLine(item["distance"]);
        Console.WriteLine(item["latt_long"]);
        Console.WriteLine(item["location_type"]);
        Console.WriteLine(item["title"]);
        Console.WriteLine(item["woeid"]);
        Console.WriteLine();
    }

    Console.Read();
}