尝试读取JSON,但无法正常工作

时间:2019-02-13 19:17:55

标签: c# json json.net

我正在尝试使用以下代码读取JSON。下面的JSON只是完整字符串的开头,这是我实际使用的完整JSON字符串。

我正在尝试遍历MessageBox所在的所有符号,但代码从未到达那里。

我想知道我会做错什么。 MessageBoxes在下面显示一些信息吗?

        {"tickers":{"ADA/CAD":{"symbol":"ADA/CAD","timestamp":1550084131415,"datetime":"2019-02-13T18:55:31.415Z","high":0.060799,"low":0.05358,"bid":0.053814,"ask":0.054435,
        "vwap":0.054506,"open":0.060799,"close":0.057262,"last":0.057262,"baseVolume":371734.41303949,"quoteVolume":20261.755917130442,
        "info":{"a":["0.054435","1975","1975.000"],"b":["0.053814","12382","12382.000"],"c":["0.057262","399.00000000"],
        "v":["368734.41303949","371734.41303949"],"p":["0.054494","0.054506"],"t":[65,69],"l":["0.053580","0.053580"],"h":["0.060799","0.060799"],"o":"0.060799"}},   
        //I have red all JSON into responseBody string
        String responseBody = ""; 


        JObject parsedJson = JObject.Parse(responseBody);
        dynamic stuff = JObject.Parse(responseBody);
        if (stuff != null)
        {
            MessageBox.Show("This messagebox is shown");

            dynamic tickers = stuff.tickers;
            for (int i = 0; i < tickers.Count; i++)
            {
                dynamic symbol = tickers[i].symbol;
                if (symbol != null)
                {
                    //This messagebox is not shown??
                    MessageBox.Show(symbol.ToString());
                }
            }
        }

2 个答案:

答案 0 :(得分:0)

在这种情况下,您不应使用 dynamic ,因为变量类型将在运行时解析,从而使您不知道实际的类型是什么以及如何使用它。这是解决您问题的快速解决方案,因此您可以更好地了解如何使用LINQ在JObject上进行迭代。

        JObject parsedJson = JObject.Parse(responseBody);
        if (parsedJson != null)
        {
            JToken tickers = parsedJson["tickers"];
            List<string> tickerKeys = tickers.Value<JObject>()
                .Properties()
                .Select(p => p.Name)
                .ToList();

            foreach(string key in tickerKeys)
            {
                Console.WriteLine(tickers[key]["symbol"]);
            }
        }

答案 1 :(得分:0)

您的RewriteCond %{QUERY_STRING} pages/oldpage RewriteRule ^(.*)$ http://www.example.com/newpage/? [R=301,L] 对象由KeyValuePairs组成,因此您可以将其反序列化为Dictionary。

tickers

我还将您的JSON转换为类结构,因此您无需依靠//json is your JSON string var deserializedTickers = JsonConvert.DeserializeObject<TickersRoot>(json); foreach(var ticker in deserializedTickers.Tickers) { // ticker.Key is "ADA/CAD" for example // and in ticker.Value is all the data relating to that key var symbol = ticker.Value.Symbol; if (symbol != null) { MessageBox.Show(symbol.ToString()); } } 即可更有效地工作:

dynamic