Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter deserialized results on a specific value from array of JSON objects?

I am getting JSON responses from API:

"table1": [
    {
        "abc": "test",
        "def": "test1"
    },
    {
        "abc": "test2",
        "def": "User1"
    }       
]

which is binding into

public List<object>? table1 { get; set; }

I want to get the User1 using Linq/Lamda.
Below returns 0 record:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    var filteredList = table1
        .Where(item => 
        item.GetType().GetProperty("def",BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase)?.GetValue(item)?.ToString() is "User1" or "User2")
.ToList();

What is wrong with it

>Solution :

I don’t see why you attempt with System.Reflection and pattern matching is here.

Either with the help of the JSON library such as Newtonsoft.Json to read/parse the object’s field:

using Newtonsoft.Json.Linq;

string[] filters = new string[] {"User1", "User2"};
var filteredList = table1
    .Where(item => filters.Contains(JObject.FromObject(item)?.SelectToken("def").ToString()))
    .ToList();

Or if you know the structure of your Table object, you define and use the model class instead of object type:

public class Root
{
    public List<Table>? table1 { get; set; }
}

public class Table
{
    public string Abc { get; set; }
    public string Def { get; set; }
}
string[] filters = new string[] {"User1", "User2"};
var filteredList = table1
    .Where(item => filters.Contains(item.Def))
    .ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading