根据值过滤JSON

时间:2016-06-02 23:37:41

标签: c# json deserialization

我有这个对象,想根据customer_email的值过滤它。例如,我只想退回客户电子邮件为test@test.com的佣金。这是响应的简单示例。下面是我获取所有数据的方法。

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();

        ......

        RootObject response = JsonConvert.DeserializeObject<RootObject>(responseContent);

        return response;
    }
}

当我收到回复时,信息如下:

{"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"
        }]

2 个答案:

答案 0 :(得分:0)

然后,您可以使用lambda表达式轻松过滤该列表的内容。

return response.Response.Data.Commissions.Where(c => c.customerEmail==customerEmail);

这将仅返回回复Commission集合中commissions的实例。

此解决方案的副作用是将方法的返回类型从RootObject更改为IEnumerable<Commission>。这意味着此方法的调用者将无法再访问响应对象中的任何其他数据(除了佣金数据)。

答案 1 :(得分:0)

您可以在responseRootObject的序列化后立即使用简单的LINQ实现它。

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