1

I have set of JSON Objects which contains contact details, and I have to filter them based on the field when it is true.

This is the Sample Data

{ 
    "9002":{
        "Contacts": [
            {
                "Source": 0,
                "Id": 0,
                "Details": {
                    "Harlson": "9015",
                    "adssd": "9022",
                    "First Name": "Gary",
                    "Last Name": "Harlson"
                },
                "Pinned": true
            }
        ]
    }
}

I want to filter all the Details based on When Pinned becomes true using LINQ query.

2
  • that is invalid json... Commented Nov 29, 2019 at 6:26
  • 1
    Have you tried? Commented Nov 29, 2019 at 6:34

2 Answers 2

3

You could Deserialize the Json (using NewtonSoft Json) and use Linq to query the Items with Pinned=True

var rootInstance = JsonConvert.DeserializeObject<RootObject>(json);
var result = rootInstance.Id.Contacts.Where(x=>x.Pinned);

Where Classes are defined as

public class Details
{
    [JsonProperty("Harlson")]
    public string Harlson { get; set; }
    [JsonProperty("adssd")]
    public string adssd { get; set; }
    [JsonProperty("First Name")]
    public string FirstName { get; set; }
    [JsonProperty("Last Name")]
    public string LastName { get; set; }
}

public class Contact
{
    public int Source { get; set; }
    public int Id { get; set; }
    public Details Details { get; set; }
    public bool Pinned { get; set; }
}

public class Id
{
    public List<Contact> Contacts { get; set; }
}

public class RootObject
{
    [JsonProperty("9002")]
    public Id Id { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

this is great so to access the OP may use something like this var jsonString = File.ReadAllText(jsonPath); var jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString); var contacts = jsonObject.Id.Contacts.ToList(); foreach (var item in contacts) { if (item.Pinned) { //Filter Details var filterDetails = item.Details; Console.WriteLine(item.Details.LastName); } }
2

You could solve it by using JSON with LINQ:

var myObjects = JArray.Parse(json)
    .OfType<JObject>()
    .Where(j => j.Properties().First().Value["Contacts"].Any(t => (bool)t["Pinned"] == true))
    .ToList();

It all depends what you should do with the data. I would personally go with Anu Viswan's answer, but if you just need a small portion of the data this might be a viable solution.

https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.