问题
I have a JSON string stored in a database like this:
{
"Error": "Lol",
"ErrorDate": "2016-05-13T10:43:27.6365795Z",
"Application": "Business",
"UserName": "Josh",
"TraceSession": "moo"
}
The JSON string is different for each item in the table. In my application I want to deserialize this into an object, but because the JSON is always different I can't create a model.
Currently I have this:
var jObject = JsonConvert.DeserializeObject(FieldNames);
which I thought would work, but now I need to loop through the properties to get the key name and value. I tried this:
// For each property in our oject
foreach (var key in jObject.GetProperties())
{
// Create a list
var list = new List<string>();
list.Add(key.GetValue());
// Add our substitution
email.AddSubstitution($"--{ key.ToUpper() }--", list);
}
but it fails because
'object' does not contain a definition for 'GetProperties'
Does anyone know how I can solve this issue?
回答1:
var jsonData = "{\"Error\": \"Lol\",\"ErrorDate\": \"2016-05-13T10:43:27.6365795Z\",\"Application\": \"Business\",\"UserName\": \"Josh\",\"TraceSession\": \"moo\"}";
var jObj = JToken.Parse(jsonData);
foreach (JProperty property in jObj.Children())
{
Console.WriteLine(property.Name);
Console.WriteLine(property.Value);
}
回答2:
A JObject is essentially a dictionnary. You can loop through keys/values like this :
class Program
{
static void Main(string[] args)
{
const string json = "{ " +
"\"Error\": \"Lol\", " +
"\"ErrorDate\": \"2016-05-13T10:43:27.6365795Z\", " +
"\"Application\": \"Business\", " +
"\"UserName\": \"Josh\", " +
"\"TraceSession\": \"moo\" " +
" }";
var jobj = JObject.Parse(json);
foreach (var prop in jobj)
{
Console.WriteLine("Key: {0}, Value: {1}", prop.Key, prop.Value);
}
}
}
回答3:
You can only get properties from the type, not the instance.
You should call:
foreach (var key in jObject.GetType().GetProperties())
{
}
On a side note you should probably use a static type when deserializing your json
回答4:
Depending on your requirements you might be fine with using dynamic keyword:
dynamic result = JObject.Parse("{...}");
Then you can access any properties like that:
if (result.MyProperty != null)
{
}
You can also loop through dynamic object.
Since you won't have any statically typed object due to nature of your json, dynamic keyword seem like a good fit.
回答5:
If I understand your question correctly, you're not deserializing to a concrete object because your fields/keys are not certian?
In this case, I find it convenient to treat my Json objects as a Dictionary of string/object pairs and then work with it from there. I tend to use object as my value because our Json can hold all sorts of stuff. That being said, if you're certain your values are only ever strings, then you can just use string/string pairs and save some casting down the road. This can easily be achieved with the following bits:
An extension method to help us out: (This will fail if your Json isn't real Json, so wrap it in a try/catch if you need that.)
public static T Deserialize<T>(this string json)
{
return string.IsNullOrWhiteSpace(json) ? default(T) : JsonConvert.DeserializeObject<T>(json);
}
Followed by its usage: (Note, calling it statically will protect you from null values too, so use it however you want.)
var dict = yourJsonString.Deserialize<Dictionary<string, object>>();
Now to answer your original question, we can just do this:
dict.ToList().ForEach(pair =>
{
//Do your work with each pair here.
});
Some of my co workers hate using Linq to iterate like this so we can also do this:
foreach (var pair in dict)
{
//Work with each pair here.
}
And if you still want to see a list of just the keys you're working with:
dict.Keys;
来源:https://stackoverflow.com/questions/37215126/looping-through-generic-object-properties