我有了反序列化包裹在「結果」根對象數據的陣列,使用Netwonsoft.Json包從的NuGetC#接收JSON字符串,但無法反序列化
應用JSON字符串是正是這種:
{"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
這JSON字符串是從一個控制檯應用程序我做創建的,我希望它看起來像這樣https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-NEO&tickInterval=hour
我的類看起來像這樣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp2
{
public class Result
{
public string Coins { get; set; }
public decimal LastPrice { get; set; }
public decimal PercentBuyVolume { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
}
在主窗體中,我有一個函數可以從JSON(我有運行Apache的XAMPP)的URL下載並將其反序列化到一個數組中。它看起來像這樣:
private void DownloadBittrexData()
{
int PanelID = 0;
var Coin = new List<string>();
var LastPrice = new List<decimal>();
var PercentBuyVolume = new List<decimal>();
var MACD1M = new List<bool>();
var MACD30M = new List<bool>();
var MACD1H = new List<bool>();
var MACD1D = new List<bool>();
var client = new WebClient();
var URL = client.DownloadString("http://localhost/test.json");
Console.WriteLine("Json String from URL: " + URL);
var dataDeserialized = JsonConvert.DeserializeObject<RootObject>(URL);
foreach (var data in dataDeserialized.results)
{
Coin.Add(data.Coins);
LastPrice.Add(data.LastPrice);
PercentBuyVolume.Add(data.PercentBuyVolume);
}
int sizeOfArrayClose = Coin.Count - 1;
for (int i = 0; i <= sizeOfArrayClose; i++)
{
Console.WriteLine("Coin: " + Coin[i]);
Console.WriteLine("Lastprice: " + LastPrice[i]);
Console.WriteLine("PBV: " + PercentBuyVolume[i]);
}
}
Newtonsoft.Json是在窗體的開頭System.Net一起申報當然
using System.Net;
using Newtonsoft.Json;
輸出看起來是這樣的:
Json String from URL: {"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
Coin:
Lastprice: 0
PBV: 0
Coin:
Lastprice: 0
PBV: 0
這就像下載它後無法反序列化它。 我該怎麼辦?非常感謝你。
json是正確的。你得到哪個錯誤? –
在該JSON字符串中,沒有稱爲LastPrice和PercentByVolume的字段。你有沒有顯示出正在處理的映射代碼? –
不,但我想我得到了解決方案,這要感謝David Watts。 我需要在'public Class Result {}內調用對象,就像在Json字符串中調用它們一樣。 Infact現在輸出正確! JSON String URL:{「results」:[{「Coin」:「SBD」,「LP」:0.000269,「PBV」: - 54.36,「MACD1M」:true,「MACD30M」:true,「MACD1H 「:真正的」 MACD1D 「:真正},{」 硬幣 「:」 XMR」, 「LP」:0.027135, 「PBV」:11.44, 「MACD1M」:真實的, 「MACD30M」:真實的, 「MACD1H」:真實, 「MACD1D」:真正}]} 硬幣:SBD Lastprice:0,000269 PBV:-54,36 硬幣:XMR Lastprice:0,027135 PBV:11,44' 感謝@DavidWattsË感恩教堂mille @Piero Alberto – Revengeic3