C# 在C中读取AppInsights的JSON输出#

C# 在C中读取AppInsights的JSON输出#,c#,json,azure-application-insights,C#,Json,Azure Application Insights,我想阅读C#控制台应用程序中的AppInsights API输出 WebClient wc = new WebClient(); wc.BaseAddress = "https://api.applicationinsights.io/v1/apps/AppInsighID/query?query=requests|where timestamp>= ago(1h)|limit 100"; wc.Headers.Add("Host", "api.applicationinsights.io

我想阅读C#控制台应用程序中的AppInsights API输出

WebClient wc = new WebClient();
wc.BaseAddress = "https://api.applicationinsights.io/v1/apps/AppInsighID/query?query=requests|where timestamp>= ago(1h)|limit 100";
wc.Headers.Add("Host", "api.applicationinsights.io");
wc.Headers.Add("x-api-key", "key");

string json = wc.DownloadString("");

JObject jsonObject = JObject.Parse(json);

//With this, i got values for Rows

var rowsObject = jsonObject["tables"][0]["rows"];
现在值在数组中,在rowObject下,那么如何读取它呢

我还想知道在阅读json字符串时应该遵循的最佳实践

我可以看到这样的数据

{
"tables": [
    {
        "name": "PrimaryResult",
        "columns": [
            {
                "name": "timestamp",
                "type": "datetime"
            },
            {
                "name": "id",
                "type": "string"
            },
            {
                "name": "source",
                "type": "string"
            },
            {
                "name": "name",
                "type": "string"
            },
            {
                "name": "url",
                "type": "string"
            },
            {
                "name": "success",
                "type": "string"
            },
            {
                "name": "resultCode",
                "type": "string"
            },
            {
                "name": "duration",
                "type": "real"
            },
            {
                "name": "performanceBucket",
                "type": "string"
            },
            {
                "name": "itemType",
                "type": "string"
            },
            {
                "name": "customDimensions",
                "type": "dynamic"
            },
            {
                "name": "customMeasurements",
                "type": "dynamic"
            },
            {
                "name": "operation_Name",
                "type": "string"
            },
            {
                "name": "operation_Id",
                "type": "string"
            },
            {
                "name": "operation_ParentId",
                "type": "string"
            },
            {
                "name": "operation_SyntheticSource",
                "type": "string"
            },
            {
                "name": "session_Id",
                "type": "string"
            },
            {
                "name": "user_Id",
                "type": "string"
            },
            {
                "name": "user_AuthenticatedId",
                "type": "string"
            },
            {
                "name": "user_AccountId",
                "type": "string"
            },
            {
                "name": "application_Version",
                "type": "string"
            },
            {
                "name": "client_Type",
                "type": "string"
            },
            {
                "name": "client_Model",
                "type": "string"
            },
            {
                "name": "client_OS",
                "type": "string"
            },
            {
                "name": "client_IP",
                "type": "string"
            },
            {
                "name": "client_City",
                "type": "string"
            },
            {
                "name": "client_StateOrProvince",
                "type": "string"
            },
            {
                "name": "client_CountryOrRegion",
                "type": "string"
            },
            {
                "name": "client_Browser",
                "type": "string"
            },
            {
                "name": "cloud_RoleName",
                "type": "string"
            },
            {
                "name": "cloud_RoleInstance",
                "type": "string"
            },
            {
                "name": "appId",
                "type": "string"
            },
            {
                "name": "appName",
                "type": "string"
            },
            {
                "name": "iKey",
                "type": "string"
            },
            {
                "name": "sdkVersion",
                "type": "string"
            },
            {
                "name": "itemId",
                "type": "string"
            },
            {
                "name": "itemCount",
                "type": "int"
            }
        ],
        "rows": [
            [
                "2020-01-16T07:07:35.8423912Z",
                "ID",
                "",
                "POST ",
                "https://",
                "True",
                "200",
                57.679,
                "<250ms",
                "request",
                "{\"Product Name\":\"Name\",\"Subscription Name\":\"Name\",\"Operation Name\":\"AdvancedSearch\",\"ApimanagementRegion\":\"Region\",\"ApimanagementServiceName\":\"Name\",\"Apim Request Id\":\"ID\",\"Request-Body\":\"{\\\"P1\\\":25,\\\"P2\\\":1,\\\"P3\\\":\\\"All \\\",\\\"P4\\\":\\\"Earliest\\\",\\\"P5\\\":\\\"Extended\\\",\\\"P6\\\":\\\"All \\\",\\\"P6\\\":\\\"Latest\\\",\\\"queryList\\\":[{\\\"P7\\\":\\\"physics\\\",\\\"P8\\\":\\\"A1\\\",\\\"operator\\\":\\\"\\\"}]}\",\"Cache\":\"None\",\"P9\":\"195.43.22.145\",\"API Name\":\"Name\",\"HTTP Method\":\"POST\"}",
                "{\"Response Size\":776,\"Request Size\":1092,\"Client Time (in ms)\":0}",
                "POST ",
                "ID",
                "ID",
                "",
                "",
                "",
                "1",
                "",
                "",
                "PC",
                "",
                "",
                "0.0.0.0",
                "Milan",
                "Milan",
                "Italy",
                "",
                "Value1",
                "Value2",
                "ID1",
                "AppInsight Name",
                "Name",
                "apim:0.12.885.0",
                "ID",
                1
            ]
        ]
    }
]
}
{
“表格”:[
{
“名称”:“PrimaryResult”,
“栏目”:[
{
“名称”:“时间戳”,
“类型”:“日期时间”
},
{
“名称”:“id”,
“类型”:“字符串”
},
{
“名称”:“来源”,
“类型”:“字符串”
},
{
“名称”:“名称”,
“类型”:“字符串”
},
{
“名称”:“url”,
“类型”:“字符串”
},
{
“名称”:“成功”,
“类型”:“字符串”
},
{
“名称”:“结果代码”,
“类型”:“字符串”
},
{
“名称”:“持续时间”,
“类型”:“真实”
},
{
“名称”:“performanceBucket”,
“类型”:“字符串”
},
{
“名称”:“项目类型”,
“类型”:“字符串”
},
{
“名称”:“自定义维度”,
“类型”:“动态”
},
{
“名称”:“自定义测量”,
“类型”:“动态”
},
{
“名称”:“操作名称”,
“类型”:“字符串”
},
{
“名称”:“操作Id”,
“类型”:“字符串”
},
{
“名称”:“操作\u父ID”,
“类型”:“字符串”
},
{
“名称”:“操作源”,
“类型”:“字符串”
},
{
“名称”:“会话Id”,
“类型”:“字符串”
},
{
“名称”:“用户Id”,
“类型”:“字符串”
},
{
“名称”:“用户\u身份验证ID”,
“类型”:“字符串”
},
{
“名称”:“用户\帐户ID”,
“类型”:“字符串”
},
{
“名称”:“应用程序版本”,
“类型”:“字符串”
},
{
“名称”:“客户类型”,
“类型”:“字符串”
},
{
“名称”:“客户机模型”,
“类型”:“字符串”
},
{
“名称”:“客户端”,
“类型”:“字符串”
},
{
“名称”:“客户IP”,
“类型”:“字符串”
},
{
“名称”:“客户城市”,
“类型”:“字符串”
},
{
“名称”:“客户州或省”,
“类型”:“字符串”
},
{
“名称”:“客户\国家或地区”,
“类型”:“字符串”
},
{
“名称”:“客户端浏览器”,
“类型”:“字符串”
},
{
“名称”:“cloud_RoleName”,
“类型”:“字符串”
},
{
“名称”:“cloud_RoleInstance”,
“类型”:“字符串”
},
{
“名称”:“appId”,
“类型”:“字符串”
},
{
“名称”:“appName”,
“类型”:“字符串”
},
{
“姓名”:“艾奇”,
“类型”:“字符串”
},
{
“名称”:“sdkVersion”,
“类型”:“字符串”
},
{
“名称”:“项目ID”,
“类型”:“字符串”
},
{
“名称”:“itemCount”,
“类型”:“int”
}
],
“行”:[
[
“2020-01-16T07:07:35.8423912Z”,
“身份证”,
"",
“职位”,
“https://”,
“真的”,
"200",
57.679,

“您可以反序列化Json并获取行信息。例如

var result = JsonConvert.DeserializeObject<RootObject>(str);
var rowData = result.tables.SelectMany(x=>x.rows.SelectMany(c=>c));
public class Dto
{
    [DtoDefinition(0)]
    public DateTime CurrentDate{get;set;}
    [DtoDefinition(1)]
    public string ID{get;set;}
    [DtoDefinition(2)]
    public string Url{get;set;}
    [DtoDefinition(11,true,typeof(Response))]
    public Response Json1{get;set;}
}

public class Response
{
    [JsonProperty("Response Size")]
    public string ResponseSize{get;set;}

    [JsonProperty("Request Size")]
    public string RequestSize{get;set;}

    [JsonProperty("Client Time (in ms)")]
    public int ClientTime{get;set;}
}
其中RootObject定义为

public class Column
{
    public string name { get; set; }
    public string type { get; set; }
}

public class Table
{
    public string name { get; set; }
    public List<Column> columns { get; set; }
    public List<List<string>> rows { get; set; }
}

public class RootObject
{
    public List<Table> tables { get; set; }
}
public Dto AssignValues(List<string> row)
{
    var dto = new Dto();
    var properties = typeof(Dto).GetProperties().Where(x=>x.GetCustomAttributes<DtoDefinitionAttribute>().Any());
    foreach(var property in properties)
    {
        var attribute = property.GetCustomAttribute<DtoDefinitionAttribute>();
        if(attribute.IsJson)
        {
            var jsonData = row[attribute.Order].ToString();
            var deserializedData = JsonConvert.DeserializeObject(jsonData,attribute.JsonDataType);
            property.SetValue(dto,deserializedData);
        }
        else
        {
            property.SetValue(dto,Convert.ChangeType(row[attribute.Order],property.PropertyType));
        }
    }
    return dto;
}
或用于非平坦结果

var rowData = result.tables.SelectMany(x=>x.rows.Select(c=>c))
                           .Where(x=>!string.IsNullOrEmpty(x.ToString()));
更新

根据注释,要检索信息并根据值在数组中的位置将其解析为Dto,可以执行以下操作

您可以从如下定义属性开始

public class DtoDefinitionAttribute:Attribute
{

    public DtoDefinitionAttribute(int order)=>Order = order;
    public DtoDefinitionAttribute(int order,bool isJson,Type jsonDataType)
    {
        Order = order;
        JsonDataType = jsonDataType;
        IsJson = isJson;
    }
    public bool IsJson{get;} = false;
    public int Order{get;}
    public Type JsonDataType {get;}
}
然后,您可以使用数组中相应值的索引来装饰Dto属性。此外,如果Json字符串预期为Json,那么您也可以使用属性来指示它,例如
ClientTime
属性中所示

var result = JsonConvert.DeserializeObject<RootObject>(str);
var rowData = result.tables.SelectMany(x=>x.rows.SelectMany(c=>c));
public class Dto
{
    [DtoDefinition(0)]
    public DateTime CurrentDate{get;set;}
    [DtoDefinition(1)]
    public string ID{get;set;}
    [DtoDefinition(2)]
    public string Url{get;set;}
    [DtoDefinition(11,true,typeof(Response))]
    public Response Json1{get;set;}
}

public class Response
{
    [JsonProperty("Response Size")]
    public string ResponseSize{get;set;}

    [JsonProperty("Request Size")]
    public string RequestSize{get;set;}

    [JsonProperty("Client Time (in ms)")]
    public int ClientTime{get;set;}
}
现在,您可以使用使用

var listDto = new List<Dto>();
foreach(var row in rowData)
{
    listDto.Add(AssignValues(row));
}
var listDto=new List();
foreach(rowData中的变量行)
{
添加(赋值(行));
}
其中赋值定义为

public class Column
{
    public string name { get; set; }
    public string type { get; set; }
}

public class Table
{
    public string name { get; set; }
    public List<Column> columns { get; set; }
    public List<List<string>> rows { get; set; }
}

public class RootObject
{
    public List<Table> tables { get; set; }
}
public Dto AssignValues(List<string> row)
{
    var dto = new Dto();
    var properties = typeof(Dto).GetProperties().Where(x=>x.GetCustomAttributes<DtoDefinitionAttribute>().Any());
    foreach(var property in properties)
    {
        var attribute = property.GetCustomAttribute<DtoDefinitionAttribute>();
        if(attribute.IsJson)
        {
            var jsonData = row[attribute.Order].ToString();
            var deserializedData = JsonConvert.DeserializeObject(jsonData,attribute.JsonDataType);
            property.SetValue(dto,deserializedData);
        }
        else
        {
            property.SetValue(dto,Convert.ChangeType(row[attribute.Order],property.PropertyType));
        }
    }
    return dto;
}
public Dto赋值(列表行)
{
var dto=新的dto();
var properties=typeof(Dto).GetProperties()。其中(x=>x.GetCustomAttributes().Any());
foreach(属性中的var属性)
{
var attribute=property.GetCustomAttribute();
if(attribute.IsJson)
{
var jsonData=row[attribute.Order].ToString();
var deserializedData=JsonConvert.DeserializeObject(jsonData,attribute.JsonDataType);
SetValue(dto,反序列化数据);
}
其他的
{
属性。设置值(dto,转换