遍历通用对象属性 [英] Looping through generic object properties

查看:122
本文介绍了遍历通用对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的数据库中存储了一个JSON字符串:

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"
}

表中每个项目的JSON字符串都不同. 在我的应用程序中,我想将其反序列化为一个对象,但是由于JSON总是不同,所以我无法创建模型.

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.

目前我有这个:

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);
}

但是失败了,因为

对象"不包含"GetProperties"的定义

'object' does not contain a definition for 'GetProperties'

有人知道我该如何解决这个问题?

Does anyone know how I can solve this issue?

推荐答案

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);
}

这篇关于遍历通用对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆