如何遍历JSON对象(到目前为止我尝试过的所有内容都失败了)。 [英] How do I loop through a JSON object (everything I've tried so far has failed).

查看:81
本文介绍了如何遍历JSON对象(到目前为止我尝试过的所有内容都失败了)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我觉得这是一个非常容易解决的问题,但我似乎无法让我的代码工作!



我想做的就是遍历JSON对象并将相关的Object项目发布到我的MVC网页上。



以下是我的代码(我保持这个非常基本,所以我可以在第一时间得到正确的基础知识)



但是,我一直收到以下错误:Newtonsoft.Json.Linq.JProperty'不包含'alertName''的定义。



我知道我目前没有使用Model属性,但是,在我尝试过的其他尝试中。



非常感谢任何帮助。



我的尝试:



控制器代码:





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:


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:

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

    }





这是JSON:





This is the JSON:

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

推荐答案

这与其他有关反序列化JSON数据的问题类似。我写了一篇文章,介绍了各种工具以及如何解码各种类型的JSON数据:在C#中使用JSON& VB [ ^ ]



为了帮助您走上正轨,我已经使用 JSON Utils [ ^ ]它给了我这个:

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:
public class Alarm
{
    [JsonProperty("unit")]
    public string Unit { get; set; }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



现在解码,使用上面文章链接中的助手类:


Now to decode, using the helper class from the article link above:

Result = JsonHelper.ToClass<Example>(rawJson);



其中 rawJson 是一个带有JSON的字符串对象数据。


where rawJson is a string object with the JSON data.


简短的回答是你的模型与你的JSON文档不匹配。您当前正在尝试的代码(不使用您的模型)也不会。我会忽略后者,因为这似乎是试图修复前者。



你的JSON文档只有一个 JObject 位于最外层,而不是数组。该单个对象包含两个属性 data error 。其中一个属性( data )包含一组值。



所以,从那开始:



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





接下来,您需要查看 AlertObject 实际上包含。它似乎包含五个属性(数据类型实际上很重要)。





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





我会让你正确地找出 AlertParameter的模型基于以上所述。最后,成员,名称和数据类型都需要与您的JSON文档相匹配。如果你只是靠近,你会得到一个例外告诉你。而且,在这种情况下,简单地在其中抛出一个动态关键字将无法解决您的问题:)



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 :)


我使用了一个javascript代码jQuery用任何结构遍历任何json对象,并返回一个HTML表来显示json对象内容。我希望这段代码可以帮助你:

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 = '';


这篇关于如何遍历JSON对象(到目前为止我尝试过的所有内容都失败了)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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