1

I am using Application Insight to log CustomEvent. I would like querying it by code (c#). I found how to use the REST API, and using GET/Query to run a query and get the JSON result. I am trying to convert data using Proposed Answer now I am facing below issue while converting data to json from the below code. This issue occurred when I tried to get exceptions from API. Line in which I am getting the issue json2 = JsonConvert.DeserializeObject<List<dynamic>>(a.Trim()); below error I am getting:

Unterminated string. Expected delimiter: ". Path '[15]', line 1, position 2017.

enter image description here

static void Main(string[] args)
    {

        string URL =
    "https://api.applicationinsights.io/v1/apps/{0}/{1}";

        string apikey = "xxxxx";
        string appid = "xxxx";
        string query = "query?query=customEvents| where timestamp >ago(30d)| top 5 by timestamp";

        string result = "";

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("x-api-key", apikey);

        var req = string.Format(URL, appid, query);

        HttpResponseMessage response = client.GetAsync(req).Result;
        if (response.IsSuccessStatusCode)
        {
            result = response.Content.ReadAsStringAsync().Result;
        }
        else
        {
            result = response.ReasonPhrase;
        }

        //get the schema of the results, like how many columns and each columns' name
        string schema = result.Remove(0, result.IndexOf("\"columns\":") + 1);
        schema = schema.Remove(schema.IndexOf("],")).Remove(0, schema.IndexOf("["));
        schema = schema + "]";

        //define a dictionary for storing structured results
        Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

        //convert schema string to json
        var json = JsonConvert.DeserializeObject<List<dynamic>>(schema);

        foreach (var item in json)
        {
            var t1 = ((JObject)item).First;
            var t2 = ((JObject)item).Last;

            string s1 = t1.ToString();

            List<string> list = new List<string>();
            dict.Add(s1.Replace("\"name\":", "").Trim(), list);
        }


        //add the value to the dictionary
        //format the string
        string new_content = result.Remove(0, result.IndexOf("\"rows\":[")).Replace("\"rows\":[", "").Replace("]}]}", "");

        //add each row of value to an array
        var row_array = new_content.Split(']');

        foreach (var t in row_array)
        {
            //if the row is empty, ignore it
            if (t.Length == 0) continue;

            int count = 0;
            string a = "";
            List<dynamic> json2 = null;

            if (t.StartsWith(","))
            {
                a = t.Remove(0, 1) + "]";
                json2 = JsonConvert.DeserializeObject<List<dynamic>>(a.Trim());
            }
            else if (!t.EndsWith("]"))
            {
                a = t + "]";

                json2 = JsonConvert.DeserializeObject<List<dynamic>>(a.Trim());
            }

            foreach (var item in json2)
            {
                var s2 = ((JValue)item).ToString();
                dict[dict.Keys.ElementAt(count)].Add(s2);
                count++;
            }
        }

        Console.WriteLine("---done---");
        Console.ReadLine();
    }
usman mehmood
  • 112
  • 1
  • 6
  • You might try to create a class model for the result and deserialize into this model. Then you would not need to parse the json. – Martin Staufcik Apr 14 '20 at 15:28
  • I further looked into the issue it is due to the data we have dynamic object within a object having [] bracts in it. when code is trying to split using //add each row of value to an array var row_array = new_content.Split(']'); it is causing the issue – usman mehmood Apr 14 '20 at 15:57
  • if you would consider also the class model, here is a tool that will generate the classes for you from json http://json2csharp.com/ – Martin Staufcik Apr 14 '20 at 16:44
  • Thank you for the reply but it is not generating the classes, I already checked the json it is vaild that is coming from API – usman mehmood Apr 14 '20 at 17:13
  • Please copy and paste the stack trace instead of posting an image if you think it's relevant. See [Why are images of text, code and mathematical expressions discouraged?](https://meta.stackexchange.com/questions/320052/why-are-images-of-text-code-and-mathematical-expressions-discouraged/320060#320060) for details. – Super Jade Jul 11 '20 at 06:51

0 Answers0