Search code examples
c#iosjsonxamarin.formsjson.net

C# - Search JSON Package for an ID


I'm building an app in Xamarin Forms - C# and I have a JSON package that has a collection of records that have IDs associated with them.

For example, here's the JSON response package:

{
   "number": "100",
   "balance": "30.000000"
},
{
   "number": "101",
   "balance": "100.000000"
},
{
   "number": "103",
   "balance": "50.000000"
},

Here's my code that pulls out all the values:

var GetGiftCardBalanceUrl = "https://example.com/wp-json/wc-pimwick/v1/pw-gift-cards";

var httpClient = new HttpClient();
var response = await httpClient.GetAsync(GetGiftCardBalanceUrl);

HttpContent content = response.Content;
var json = await content.ReadAsStringAsync();

GiftCardsRoot mygiftcards = JsonConvert.DeserializeObject<GiftCardsRoot>(json);

And here's my model:

public class GiftCardsRoot
{
   public List<GiftCardsMyArray> GiftCardsMyArray { get; set; }
}

public class GiftCardsMyArray
{
   public string number { get; set; }
   public string balance { get; set; }
}

How would I retrieve the balance value if I were to enter the number value in C#?

For example:

If JSON response package number value contains:

101

Then it would return:

"100.00000"

NOTE. The API that I'm using is very new and they don't have any endpoints to retrieve records based off IDs yet so I'm looking for a workaround for now.


Solution

  • I'd suggest using:

    var bob = mygiftcards.GiftCardsMyArray.FirstOrDefault(z => z.number == "101")
    

    This will find the first element in the array that has the number of 101.