Reputation: 978
I have a json string like so (there are many properties but just including few values): [{"Key":"ID","Value":"123"},{"Key":"Status","Value":"New"},{"Key":"Team","Value":"South"}]
I have a class representing the values
public class CustomObject
{
public string ID { get; set; }
public string Status { get; set; }
public string Team { get; set; }
//Other props
}
So even though the JSON is an array of these objects containing Key:x, Value:y
, the whole structure is really just an instance of my CustomObject
class. This is the way the json is given to me. How can I convert this to a type of CustomObject
?
Upvotes: 1
Views: 1588
Reputation: 11364
You can do something like this. Create a new class that deserializes the JSON you get to a class of KeyValue pairs. Then take the values from this class based on the Keys you are interested in.
public class CustomObject
{
public CustomObject() { }
public CustomObject(List<KeyValueClass> jsonObject) // Use of Reflection here
{
foreach (var prop in typeof(CustomObject).GetProperties())
{
prop.SetValue(this, jsonObject.FirstOrDefault(x => x.Key.Equals(prop.Name))?.Value, null);
}
}
public string ID { get; set; }
public string Status { get; set; }
public string Team { get; set; }
}
public class KeyValueClass
{
[JsonProperty("Key")]
public string Key { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
and following is how you'd deserialize it.
var obj = JsonConvert.DeserializeObject<List<KeyValueClass>>(json);
var customObj = new CustomObject()
{
ID = obj.FirstOrDefault(x => x.Key.Equals("ID"))?.Value,
Status = obj.FirstOrDefault(x => x.Key.Equals("Status"))?.Value,
Team = obj.FirstOrDefault(x => x.Key.Equals("Team"))?.Value
};
var customObj2 = new CustomObject(obj); // Using constructor to build your object.
Note: Based on convention, you should use UpperCase first letter for the variable names in the class. Use of JsonProperty helps in conforming to that standard.
Upvotes: 1