Retrieve and parse the JSON file from the URL in C#

Asked 2 years ago, Updated 2 years ago, 122 views

http://cathval.com/csharp/4159
I found out how to handle JSON data by referring to this site, but how can I receive JSON information from WebAPI like the URL below in String?

http://weather.livedoor.com/forecast/webservice/json/v1?city=400040

c# json http

2022-09-30 14:48

3 Answers

HttpWebRequest class may be used, but
It is easy to use the WebClient.DownloadString method in the WebClient class.

Examples of use:

using System;
using System.IO;
using System.Net;

namespace HTTPGET
{
    class HttpGet
    {
        static void Main (string[]args)
        {
            using(WebClient=newWebClient())
            {
                string str = webClient.DownloadString("http://weather.livedoor.com/forecast/webservice/json/v1?city=400040");
                Console.Write(str);
            }
        }
    }
}


2022-09-30 14:48

If you wanted to create a RESTful service, the ASP.NET Web API was designed with this goal in mind.

For example, HttpClient class makes it easy to receive async.

using System;
using System.Threading.Tasks;
You can install `System.Net.Http` or `Microsoft.AspNet.WebApi.Client` in using System.Net.Http;//nuget.


namespace httpclient_test
{
    class program
    {
        static void Main (string[]args)
        {
            stringuri="http://weather.livedoor.com/forecast/webservice/json/v1?city=400040";
            GetString(uri).Wait();
        }

        public static async Task GetString (stringuri)
        {
            using(var httpClient=new HttpClient())
            {
                string response = wait httpClient.GetStringAsync(uri);
                Console.Write(response);
            }
        }
    }
}


2022-09-30 14:48

When sending HTTP requests over .NET, the basic is WebRequest, and WebClient and HttpClient also use WebRequest internally.

using System;
using System.IO;
using System.Net;
using System.Text;

static class program
{
    static void Main (string[]args)
    {
        var req = WebRequest.Create("http://weather.livedoor.com/forecast/webservice/json/v1?city=400040");

        using(var res=req.GetResponse())
        using(varsr=new StreamReader(res.GetResponseStream(), Encoding.ASCII))
        {
            Console.WriteLine(sr.ReadToEnd());
        }

        Console.ReadKey();
    }
}

Also, if you only want the analysis results, you should use Stream instead of String.

dynamic json; 
using(var res=req.GetResponse())
using(vars=res.GetResponseStream())
{
    json=DynamicJson.Parse(s);
}


2022-09-30 14:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.