Click here to Skip to main content
16,018,797 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
 var data = JsonConvert.DeserializeObject<Root>(jsonResponse).Data;
                                               
foreach (var dict in data)
 {


// here i need to access all key values as a variable 
ex:var id= 3780b945-d24c-4742-bd11-71c90a0728cb;
var reference =14660;
var LicenseNumber = 2015013464;

}





in data i'm getting below JsonData:


{
  "Data": [
    {
      "Id": "3780b945-d24c-4742-bd11-71c90a0728cb",
      "Reference": 14660,
      "LicenseNumber": "2015013464",
      "Name": "Alegre Belle",
      "Headline": "Modern masterpiece with vast terracing and designer finishes.",
      "Summary": "",
      "Description": "Alegre Belle’s impressive modern style and beautiful interior spaces are a del",
      "Benefits": null,
      "OtherInfo": null,
      "PropertyType": "Villa",
      "MinimumStay": 3,
      "Active": true,
      "Sleeps": 10,
      "Bedrooms": 5,
      "Bathrooms": 5,
      "Kitchens": 1,
      "DiningCapacity": 10,
      "LivingAreaSize": 700,
      "Continent": "Europe",
      "Country": "Spain",
      "StateProvince": "Balearic Islands",
      "Region": "Ibiza",
      "SubRegion": "San Jose",
      "AddressLine2": null,
      "Longitude": 1.292036,
      "Latitude": 38.881278,
      "Housekeeping": "Included",
      "OtherHousekeepingInfo": "4 hours daily cleaning. Concierge service and chef.",
      "ChildrenAllowed": "Yes",
      "SmokingAllowed": "No",
      "PetsAllowed": "No",
      "EventsAllowed": "N/A",
      "WheelchairAccessible": "No",
      "SecurityDeposit": 5000.00,
      "LastUpdatedAt": "2019-09-25T01:05:35.283",
      "ImageUrls": [
        "http://res.cloudinary.com/privadia/image/upload/v1562146932/alegre_belle_hq_6.jpg",
        "http://res.cloudinary.com/privadia/image/upload/v1513933158/lhscukldl22h5d9ag8or.jpg",
       oudinary.com/privadia/image/upload/v1513933207/lteai46ba6svnef8ao3v.jpg",
        "http://res.cloudinary.com/privadia/image/upload/v1513933138/jufs9ablepifpkgbzpnr.jpg"
      ],
      "Rooms": [
        {
          "Type": "Bedroom",
          "Name": "Bedroom 1",
          "Description": "Master Bedroom, double bathroom, fitted dressing room, private terrace and outdoor sitting area. This bedroom takes up the whole top floor."
        },
        {
          "Type": "Bedroom",
          "Name": "Bedroom 2 ",
          "Description": "Large double bedroom with en-suite bathroom."
        },
        
        {
          "Type": "Kitchen",
          "Name": "Kitchen 1",
          "Description": "Designer, fully equipped Boffi kitchen"
        }
      ],
      "MetaData": [
        {
          "Type": "Suitability",
          "SubType": "Trip Type",
          "Name": "Families"
        },
        {
          "Type": "Suitability",
          "SubType": "Trip Type",
          "Name": "Groups"
        },
       
        {
          "Type": "Setting & View",
          "SubType": "Setting & View",
          "Name": "Gated Community"
        },
        {
          "Type": "Features",
          "SubType": "Amenities",
          "Name": "Wifi"
        },
        {
          "Type": "Features",
          "SubType": "Amenities",
          "Name": "Air Conditioning"
        },
        
        {
          "Type": "Features",
          "SubType": "Outdoor Features",
          "Name": "Private Gates"
        }
      ],
      "Rates": [
        {
          "From": "2019-06-30T16:00:00",
          "To": "2019-07-29T10:00:00",
          "Rate": 22534.219100,
          "LengthOfStay": 7
        },
        {
          "From": "2017-04-29T00:00:00",
          "To": "2017-05-26T00:00:00",
          "Rate": 12578.763100,
          "LengthOfStay": 7
        },
       
        {
          "From": "2020-04-25T16:00:00",
          "To": "2020-05-22T10:00:00",
          "Rate": 11956.547100,
          "LengthOfStay": 7
        }
      ],
      "CalUrl": "http://api.privadia.com/api/Calendar/ICal/14660",
      "Unavailable": [
        {
          "From": "2016-07-09T16:00:00",
          "To": "2016-07-16T10:00:00"
        },
        {
          "From": "2016-07-23T16:00:00",
          "To": "2016-08-06T10:00:00"
        },
        
        {
          "From": "2019-10-26T16:00:00",
          "To": "2019-11-02T10:00:00"
        }
      ]
    }
  ],
  "Page": 1,
  "TotalCount": 1,
  "TrackingId": null
}


What I have tried:

Get key value pairs as variable values key should become variable name and value becomes respective value for a key.
 var data = JsonConvert.DeserializeObject<Root>(jsonResponse).Data;
                                               
 foreach (var dict in data)
   {


// here i need to access all key values as a variable 
ex:var id= 3780b945-d24c-4742-bd11-71c90a0728cb;
var reference =14660;
var LicenseNumber = 2015013464;

}
C#




class Root
{
    public List<Dictionary<string, object>> Data { get; set; }
}
Posted
Updated 24-Sep-19 22:14pm
v3
Comments
F-ES Sitecore 23-Sep-19 5:05am    
It's impossible to say without knowing any of the types in question. What is Root?
Arfat M 23-Sep-19 5:49am    
class Root
{
public List<dictionary<string, object="">> Data { get; set; }
}
F-ES Sitecore 23-Sep-19 5:59am    
object id;

foreach (var dict in data)
{
if (dict.ContainsKey("id"))
{
id = dict["id"];
}
}

1 solution

You never posted your json file so lets assume this is your json file :
public static readonly string json = @"{'Name': 'Avatar','ReleaseDate': '2009-8-7','Genres': 'Action'}"; 
/* This is my json file */

I prefer to use the JavascriptDeserializer instead of jsonconvert deserializer :
var serializer = new JavaScriptSerializer(); 
/* Create a new JavaScriptSerializer */
var receivedjson = serializer.Deserialize<Dictionary<string, string>>(json); 
/* Return a dictionary */

Next loop through your key value pair and you can then access both key and value with kvp.Key and kvp.Value.
C#
int i = 0;
foreach (KeyValuePair<string, string> kvp in receivedjson)
{
    i++;
    Console.WriteLine($"Key {i} is : {kvp.Key} while value {i} is : {kvp.Value}");
}

This outputs :
Key 1 is : Name while value 1 is : Avatar
Key 2 is : ReleaseDate while value 2 is : 2009-8-7
Key 3 is : Genres while value 3 is : Action

Don't forget to mark as accepted answer.

If you want an ordered dictionary. Please see OrderedDictionary Class (System.Collections.Specialized) | Microsoft Docs[^] as recommended by BillWoodruff
 
Share this answer
 
v3
Comments
BillWoodruff 23-Sep-19 10:19am    
+5 very good answer. but, remember that the .NET Dictionary does not guarantee KeyValue Pairs are in any particular order. To ensure a certain order, there are OrderedDictionary, and SortedDictionary collections.
[no name] 23-Sep-19 11:22am    
Thanks Bill. I added a reference to the ordered dictionary in my answer. I find its easier to give what they asked. They can always ask later how to extend it to a sorted collection of KVP ;)
BillWoodruff 24-Sep-19 22:20pm    
I often make comments I think add value to posts I upvote. They are never intended to imply the upvoted post is not complete, and excellent :)
[no name] 25-Sep-19 8:04am    
Indeed, and so you should. That's why I added it to my answer. It's likely OP may want sorted dictionary instead. I appreciate your input. ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900