user14139029
user14139029

Reputation:

Can't Filter JSON in C#

I'm trying to Filter the id of Connections by name e.g. return the id of connection, where the name is Equal to 12345678.

I'm able to get all of records and also the values of id & name as well.

But, I Just want to Filer it e.g. How could I only get the record's id, where the name is equal to 12345678? I wrote the code below (I know it's stupid) and it's returning the all records.

CODE

public class Alias
{
    public string name { get; set; }
}

public class Connections
{
    public Alias alias { get; set; }
    public string id { get; set; }
}

public class RootObject
{
    public List<Connections> connections { get; set; }
} 

    HttpClient hTTPClient = new HttpClient();

    UserID = "12345678";

    Uri getConnections = new Uri(string.Format("http://0.0.0.0:0000/getConnections"));
    HttpResponseMessage restponseConnections = await hTTPClient.GetAsync(getConnections);
    string contentConnections = await restponseConnections.Content.ReadAsStringAsync();
    RootObject obj = JsonConvert.DeserializeObject<RootObject>(contentConnections);

    foreach (Connections i in obj.connections)
    {
        if(!(i.alias.name == UserID))
        {
            Console.WriteLine(i.id);
        }
    }

JSON

    {
        "success": true,
        "connections": [
            {
                "typeName": "AF.ConnectionRecord"
                "alias": {
                    "name": "12345678",
                    "imageUrl": null
                },
                "endpoint": {
                    "did": null,
                    "verkey": [
                        "6KZYwhxzxWcrZnQravocia2XHyoK9V8pBVT7nBdAd5JX"
                    ],
                    "uri": "http://0.0.0.0:0000"
                },
                "state": 2,
                "id": "d0e4ccbf-5e2a-47bb-a218-78ea93a6066b",
                "createdAtUtc": "2020-10-27T08:01:43.0724247",
                "updatedAtUtc": "2020-10-27T08:01:45.7475196"
            }
        ]
    }

Upvotes: 0

Views: 133

Answers (2)

Kudzai Dube
Kudzai Dube

Reputation: 101

In your case assuming you want to get 1 record, I'd suggest you use LINQ

using System.Linq;

//Rest of your code
var recId = obj.connections.Where(c => c.alias.name == "1234567").FirstOrDefault();

Upvotes: 0

Jason
Jason

Reputation: 89129

use LINQ

using System.Linq;
...
var list = obj.connections.Where(c => c.alias.name == "xyz").ToList();

Upvotes: 1

Related Questions