Click here to Skip to main content
15,890,336 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I feel this is an incredibly easy issue to resolve, but I just can't seem to get my code to work!

All I am trying to do is loop through a JSON Object and publish relevant Object items onto my MVC web page.

Here is my code below (I've kept this very basic just so I can get the basics correct first time round)

However, I keep getting the following error: Newtonsoft.Json.Linq.JProperty' does not contain a definition for 'alertName''.

I'm aware that I'm currently not using the Model properties, however, in other attempts I've tried I have been.

Any help is greatly appreciated.

What I have tried:

Controller Code:


C#
var jsonClient = new WebClient();
            jsonClient.Credentials = new NetworkCredential("XXXX", "XXXX");
            jsonClient.Headers.Set("Content-Type", "application/json");
            jsonClient.Headers.Set("Accept", "application/json");
            var alertsSettings = jsonClient.DownloadString("http://XXXXX:XXXX/api/alerts/settings");

            dynamic alertObj = JsonConvert.DeserializeObject(alertsSettings);

            foreach (var item in alertObj)
            {
                Viewbag.Test123 = item.alertName;
            }


Model Code:

C#
public class AlertObject
    {
        public string alertName { get; set; }
        public string value { get; set; }
        public string alertMnemonic { get; set; }
        public string enabled { get; set; }
        public string unit { get; set; }
        public string warning { get; set; }
        public string sharedParam { get; set; }
        public string type { get; set; }
        public string id { get; set; }

    }


This is the JSON:

JavaScript
{
    "data": [
        {
            "id": 268500993,
            "alertName": "High CPU Usage",
            "alertMnemonic": "HIGH_CPU_USAGE",
            "enabled": true,
            "parameters": {
                "alarm": {
                    "unit": "MINUTES",
                    "value": 15
                },
                "warning": {
                    "unit": "MINUTES",
                    "value": 5
                },
                "sharedParam": {
                    "unit": "CPU",
                    "value": 70,
                    "name": "CPU Usage"
                },
                "type": "TERNARY"
            }
        },
        {
            "id": 134479876,
            "alertName": "Custom Module Changed",
            "alertMnemonic": "CUSTOM_MODULE_CHANGED",
            "enabled": false,
            "parameters": null
        },
        {
            "id": 268500992,
            "alertName": "Low JVM Memory",
            "alertMnemonic": "LOW_AVAILABLE_JVM_MEMORY",
            "enabled": true,
            "parameters": {
                "alarm": {
                    "unit": "MEMORY",
                    "value": 64
                },
                "warning": {
                    "unit": "MEMORY",
                    "value": 128
                },
                "sharedParam": {
                    "unit": "MINUTES",
                    "value": 5,
                    "name": "Time"
                },
                "type": "TERNARY"
            }
        }
	],
    "error": null
}
Posted
Updated 31-Jul-18 2:26am
v4

The short answer is that your model doesn't match your JSON document. Neither does the code (which doesn't use your model) that you're currently attempting. I'll ignore the latter, since this seems to be an attempt to fix the former.

You're JSON document has a single JObject at the outermost level, not an array. That single object consists of two properties data and error. One of these properties (data) contains an array of values.

So, start with that:

public class MyObject
{
  public List<AlertObject> data { get; set; }
  public string error { get; set; }
}


Next, you need to look at what AlertObject actually contains. It appears to contain five properties (and data type actually matters).

public class AlertObject
{
  public int id { get; set; }
  public string alertName { get; set; }
  public string alertMnemonic { get; set; }
  public bool enabled { get; set; }
  public List<AlertParameter> parameters { get; set; }
}


I'll leave you to correctly figure out the model for AlertParameter based on the above. Bottom line the members, names, and data types all need to match your JSON document. If you simply "come close", you'll get an exception telling you so. And, in that case, simply tossing a dynamic keyword in there will not resolve your problem :)
 
Share this answer
 
v2
This is similar to other questions that get asked here regarding deserializing JSON data. I've written an article that covers the tools and how to decode various types of JSON data: Working with JSON in C# & VB[^]

To help you on the right track, I've taken your RAW JSON data and created classes using JSON Utils[^] and it gave me this:
C#
public class Alarm
{
    [JsonProperty("unit")]
    public string Unit { getset; }

    [JsonProperty("value")]
    public int Value { getset; }
}

public class Warning
{
    [JsonProperty("unit")]
    public string Unit { getset; }

    [JsonProperty("value")]
    public int Value { getset; }
}

public class SharedParam
{
    [JsonProperty("unit")]
    public string Unit { getset; }

    [JsonProperty("value")]
    public int Value { getset; }

    [JsonProperty("name")]
    public string Name { getset; }
}

public class Parameters
{
    [JsonProperty("alarm")]
    public Alarm Alarm { getset; }

    [JsonProperty("warning")]
    public Warning Warning { getset; }

    [JsonProperty("sharedParam")]
    public SharedParam SharedParam { getset; }

    [JsonProperty("type")]
    public string Type { getset; }
}

public class Datum
{
    [JsonProperty("id")]
    public int Id { getset; }

    [JsonProperty("alertName")]
    public string AlertName { getset; }

    [JsonProperty("alertMnemonic")]
    public string AlertMnemonic { getset; }

    [JsonProperty("enabled")]
    public bool Enabled { getset; }

    [JsonProperty("parameters")]
    public Parameters Parameters { getset; }
}

public class Example
{
    [JsonProperty("data")]
    public IList<Datum> Data { getset; }

    [JsonProperty("error")]
    public object Error { getset; }
}

Now to decode, using the helper class from the article link above:
C#
Result = JsonHelper.ToClass<Example>(rawJson);

where rawJson is a string object with the JSON data.
 
Share this answer
 
Comments
JoshWigley 17-Jul-18 7:03am    
Hi Graeme,

Thanks for this. I've not come across this article before, so I'll read it before I try anymore attempts at resolving this issue. Appreciate the help.

Thanks,
Josh
I wrote a javascript code using jQuery to traverse any json object with any structure and return an HTML table for displaying the json object content. I hope this code help you:
var outHtml = '';
        var tblHtml = '';
        function parseJsonResult(obj) { 

            outHtml = '';
            tblHtml = '';

            $.each(obj, function (key, value) {

                tblHtml += '<tr><td class="jsonTd1">' + key + '</td>';
                parseJsonRecursive(key, value);
                tblHtml += '</tr>';
            });

            outHtml = '<div><table  class="jsonTbl">' + tblHtml + '</table></div>';

            return outHtml;
        }

        function parseJsonRecursive(key, val) {

            try {

                try {

                    try {
                        $.each(val, function (k, v) {
              
                        });

                        tblHtml += '<td><table>';
                    }
                    catch {
                        
                    }

                    $.each(val, function (k, v) {
                        tblHtml += '<tr><td class="jsonTd1">' + k + '</td>';
                        parseJsonRecursive(k, v);
                        tblHtml += '</tr>';

                    });

                    tblHtml += '</table></td>';
                }
                catch (ee) {

                    var obj = jQuery.parseJSON(val);

                    try {

                            $.each(obj, function (k, v) {

                            });

                            tblHtml += '<td><table>';
                    }
                    catch {

                    }

          

                    $.each(obj, function (k, v) {
                        tblHtml += '<tr><td class="jsonTd1">' + k + '</td>';
                        parseJsonRecursive(k, v);
                        tblHtml += '</tr>';
                    });

                    tblHtml += '</table></td>';
                }

            }
            catch (e) {
                //alert(4);
                //alert(outHtml);
                tblHtml += '<td class="jsonTd2">' + val + '</td>';

                //alert(key + ": " + val);
            }

        }


<style>
        .jsonTbl tr {
            border-style:solid;
            border-color : black;
            border-width: thin;
        }

        .jsonTd1 {
            padding-left: 10px;
            padding-right: 10px;
            border-left-style: solid;
            border-left-color: black;
            border-left-width: thin;
            color: blue;
            font-size: large;
            font-weight: bold;
        }

        .jsonTd2 {
            padding-left: 10px;
            padding-right: 10px;
        }
    </style>

To call the function:
var contentHtml = '';
		try {
			contentHtml = parseJsonResult(jsonObjectToParse));
		}
		catch{

		}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900