xyzcode xyzcode - 6 months ago 9
JSON Question

Filtering JSON based on value

I have this object and would like to filter it based on the value of customer_email. For example, I only want to return commissions where the customer email is test@test.com. This is a simplified example of what a response would look like. Below is the method where I grab all the data.

public RootObject GetData(string customerEmail)
{
var data = new Commission();
using (var httpClient = new HttpClient())
{
var requestContent = JObject.FromObject(new
{
commission_id = data.id,
customer_email = customerEmail

}).ToString();

var httpResponseMessage = httpClient.PostAsync(string.Format(.....).Result;
var responseContent = httpResponseMessage.Content.ReadAsStringAsync().Result;
RootObject response = JsonConvert.DeserializeObject<RootObject>(responseContent);

return response;
}
}


When I get the response, the information looks like this:

{"response":{
"code":"200",
"message":"OK: The request was successful. See response body for additional data.",
"data":{
"commissions":
[{
"commission_id":"12345",
"customer_email":"test@test.com"
},
{
"commission_id":"67890",
"customer_email":"fake@fake.com"
}]


Below are the classes associated with this information:

public class Commission
{
[JsonProperty(PropertyName = "commission_id")]
public string CommissionId{ get; set; }

[JsonProperty(PropertyName = "customer_email")]
public string CustomerEmail { get; set; }
}

public class Data
{
public List<Commission> Commissions { get; set; }
}

public class Response
{
public Data Data { get; set; }
}

public class RootObject
{
public Response Response { get; set; }
}

Answer

You can achieve it using simple LINQ right after serialization of response to RootObject.

return response
        .Response.Data.Commissions
        .Where(commission => commission.CustomerEmail == customerEmail);
Comments