Reputation: 37
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
Reputation: 1898
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; }
}
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
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
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