Search code examples
c#asp.netstreamasmxwebmethod

Limiting a JSON string response from an API to select attributes


Currently, I am using a [WebMethod] to call an API and get the response as a JSON string.

 public string GetFloodData()
 { ...
     WebRequest requestObj = WebRequest.Create(url);
     requestObj.Method = "GET";
     requestObj.ContentType = "application/json";

     responseObj = (HttpWebResponse)requestObj.GetResponse();
     using (Stream stream = responseObj.GetResponseStream())
     {
       StreamReader sr = new StreamReader(stream);
       strresult = sr.ReadToEnd();
       sr.Close();
     }
     return strresult;
...
}

When I call GetFloodData(), I get the following response in the browser:

<string xmlns="http://tempuri.org/">
{"ListEvents": 
[{"EventID":1,"EventName":"Debby2000","State":"PR","EventType":"Tropical or 
Extratropical","Days":5,"LSTStart":"\/Date(9666432000000000)\/",
"LSTEnd":"\/Dat e(967075200000-0000)\/"}, {...}....]}

At this point (before I parse it as a formal JSON Object), I just want to eliminate the stuff I don't want ("Days","LSTStart", and "LSTEnd") and keep what I want. How would I limit what attributes are returned in my response?


Solution

  • You can de-serialise it with a class, and in that class, you can write only the variables you do want to keep. Although, keep the structure of the Json and the class as same. Variables can be missing, but the structure should be the same