Home > Software design >  Parsing Only the First Object of Array JSON
Parsing Only the First Object of Array JSON

Time:12-31

I have the following text structure in JSON:

   {
   "Results":{
      "Burger King":{
         "Location":"New York",
         "Address":"Avenue Dalmatas, 20"
 },
      "Mcdonalds":{
         "Location":"Los Angeles",
         "Address":"Oscar Street, 50"
      }
   }
}

I managed to get the city and address results, but for that I need to mention the name of the restaurant in the code to grab the token string.

Dim JSON As String = **json here**

        Dim token As JToken
        token = JObject.Parse(JSON.ToString())
        Dim data = token.SelectToken("Results").SelectToken("Burger King").SelectToken("Location")

My question is, how can I list only the restaurants (Burger King, Mcdonalds, etc), for example, in a Listbox? So I can add some feature that checks the address and city with the user's choice, which I know and already understand how to do, but getting the token with only the names of the restaurants is being difficult for me. If i have a new restaurant name for example, I wouldn't want to include manually in the code. I have tried a lot of different ways, but the last one I have used it was the following:

Dim data = token.SelectToken("Results").SelectToken(0) 'i thought it would print 'Burger King'
'or this one
Dim data = token.SelectToken("Results")(0).ToString()

I've tried some 'For Each' loop code but I wasn't successful either. I've researched countless methods on how to do this and nothing works. I believe it's something simple that I'm either ignoring or completely forgetting.. Please give me a light! Thanks.

CodePudding user response:

I can post c# code for you, it would be easier for you to translate it to VB if you need

var jsonObject=  JObject.Parse(json);

List<string> restaurantNames= ((JObject)jsonObject["Results"]).Properties()
.Select(x=>x.Name).Distinct().ToList();

result

Burger King
Mcdonalds
  • Related