I have a C# class that receives a JSON string, and deserialises it into a dynamic.
json = @"{
"Id": "97dc4a96-43cf-48bd-9358-8f33e910594e",
"RepId": 90037,
"Something": true,
"SomethingElse": "abcdefg",
"Thing_1_of_MaybeDozens": 55
}";
dynamic jsonData = JsonConvert.DeserializeObject(json);
I can't deserialse into a class because while each JSON string will always have two known data elements (Id, and RepId), the rest of the string may have many elements that I do not know ahead of time their names, or how many of them there are.
I can always ask for jsonData.Id, or jsonData.RepId, but I do not know how many other elements there may be, nor how to refer to them.
I need something similar to JavaScript's Object.Keys(myObject).
Anyone knows how to do similar in C# with a Newtonsoft Deserialised JSON string?
CodePudding user response:
You can use Reflection:
public Dictionary<string, object> DynamicToDictionary(dynamic obj)
{
var dict = new Dictionary<string, object>();
foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(obj))
{
object obj2 = propertyDescriptor.GetValue(obj);
dict.Add(propertyDescriptor.Name, obj2);
}
return dict;
}
Now you may use the dictionary's TryGetValue(), and ContainsKey().
CodePudding user response:
try to use Newtonsoft.Json extensions
var data = JsonConvert.DeserializeObject<Data>(json);
list of keys
List<string> additionalKeys=data.AdditionalData.Select(ad => ad.Key).ToList();
output
["Something","SomethingElse","Thing_1_of_MaybeDozens"]
how to use
var id = data.Id; //97dc4a96-43cf-48bd-9358-8f33e910594e
var somethingElse = data.AdditionalData["SomethingElse"]; // abcdefg
class
public class Data
{
// normal deserialization
public string Id { get; set; }
public long RepId { get; set; }
//additional data
[JsonExtensionData]
public Dictionary<string, object> AdditionalData {get;set;}
}
