countmora
countmora

Reputation: 37

How do I get the key and it's object from a JSON file in c# using JSON.net?

I have a JSON file like this

    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    }

and a class like this:

public class MyClass
    {
        private string key;
        private string object;

        public double Key
        {
            get { return key; }
            set { key = value; }
        }

        public string Object
        {
             get { return object; }
             set { object = value; }
        }

         public MyClass(string key, string object)
        {
                this.key = key;
                this.object = object;
        }
    }

And ideally I want to get a List<String> with the values from the JSON file. How do I achieve this?

Upvotes: 0

Views: 93

Answers (3)

Gokulan P H
Gokulan P H

Reputation: 1898

  1. Create a class similar to your json structure, you can use http://json2csharp.com/

      public class MyClass
    
      {
    
      public string key1 { get; set; }
    
      public string key2 { get; set; }
    
      public string key3 { get; set; }
    
      }
    
  2. Create a method taking the json as input parameter and add the values to the list, then return it.

public list<string> GetValues(MyClass myClassObjects)
{
list<String> valueList = new list<String>();
for(int i=0; i< myClassObjects[0].count ; i++)
{
valueList.add(myClassObjects[0][i].toString());
}
return valueList;
}

Upvotes: 0

Brian Rogers
Brian Rogers

Reputation: 129707

I would just deserialize this JSON into a Dictionary<string, string>:

var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Then if you just want a list of values you can do:

var values = dict.Values.ToList();

Upvotes: 0

meJustAndrew
meJustAndrew

Reputation: 6613

You can deserialize into a dynamic object, then access directly what value you want:

dynamic obj = JObject.Parse(yourJson);
string key1 = obj.key1;
string key2 = obj.key2;
string key3 = obj.key3;

Upvotes: 2

Related Questions