简体   繁体   中英

How to Request Specific Object From JSON URL with C# WebClient

Following code returns entire JSON objects but I need to Filter to some specific Object, for example I need to get only the "layers" or tiltle can you please let me know how to do this is C#?

Do I have to create an HttpWebRequest object for this? if so where should I pass the requested data?

using (WebClient wc = new WebClient())
   {
    var json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
    Console.WriteLine(json);
   }

I already tried this but it is also returning everything

class Program
{
    private const string URL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson";
    private const string DATA = @"{{""layers"":""Layers""}}";
    static void Main(string[] args)
    {

       CreateObject();

    }
    private static void CreateObject()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = DATA.Length;
        using (Stream webStream = request.GetRequestStream())
        using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
        {
            requestWriter.Write(DATA);
        }

        try
        {
            WebResponse webResponse = request.GetResponse();
            using (Stream webStream = webResponse.GetResponseStream())
            {
                if (webStream != null)
                {
                    using (StreamReader responseReader = new StreamReader(webStream))
                    {
                        string response = responseReader.ReadToEnd();
                        Console.WriteLine(response);
                        Console.ReadLine();
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("-----------------");
            Console.WriteLine(e.Message);
            Console.ReadLine();
        }

    }

}

If you need the info related to the layers array object then you can use following code

 using (var wc = new WebClient())
 {
     string json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
     dynamic data = Json.Decode(json);
     Console.WriteLine(data.layers[0].id);
     Console.WriteLine(data.layers[0].name);
     Console.WriteLine(data.documentInfo.Title);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM