我有了反序列化包裹在“结果”根对象数据的阵列,使用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