C#接收json字符串但无法反序列化

时间:2017-09-15 11:51:23

标签: c# json serialization foreach jsonresult

我有一个应用程序必须使用NuGet中的Netwonsoft.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; }
    }
}

在Main表单中,我有一个从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

下载后它无法反序列化。 我该怎么办?非常感谢你。

3 个答案:

答案 0 :(得分:2)

您的媒体资源名称不会映射到JSON中的字段名称。您可以重命名C#属性以匹配JSON,但这会导致下游代码无法读取。

相反,您应该使用JsonPropertyAttribute将您的属性(具有漂亮,可读的名称)映射到JSON中显示的名称:

public class Result
{
    public string Coin { get; set; } //didn't bother here: changed property name to Coin
    [JsonProperty("LP")]
    public decimal LastPrice { get; set; }
    [JsonProperty("PBV")]
    public decimal PercentBuyVolume { get; set; }
}

答案 1 :(得分:1)

你的模型应该像这样反序列化json

public class Result
{
    public string Coin { get; set; }
    public double LP { get; set; }
    public double PBV { get; set; }
    public bool MACD1M { get; set; }
    public bool MACD30M { get; set; }
    public bool MACD1H { get; set; }
    public bool MACD1D { get; set; }
}

public class RootObject
{
    public List<Result> results { get; set; }
}

LastPrice and PercentBuyVolume在您的模型中不可用,这是导致错误的原因。

答案 2 :(得分:0)

我在我的系统上尝试了您的确切代码,我能够按预期检索结果。希望这有帮助,这很容易理解。

这是主要的课程

 static void Main(string[] args)
    {

        RootObject configfile = LoadJson();

        foreach (var tResult in configfile.results)
        {
            Console.WriteLine("Coin: " + tResult.Coin);
            Console.WriteLine("Lastprice: " + tResult.LP);
            Console.WriteLine("PBV: " + tResult.PBV);
        }


        Console.ReadLine();

    }

LoadJson函数将是

 private static RootObject LoadJson()
    {
        string 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}]}";



        RootObject configs = Deserialize<RootObject>(json);
        return configs;
    }

和反序列化函数将是

private static T Deserialize<T>(string json)
    {
        T unsecureResult;
       string _DateTypeFormat = "yyyy-MM-dd HH:mm:ss";
        DataContractJsonSerializerSettings serializerSettings = new DataContractJsonSerializerSettings();
        DataContractJsonSerializer serializer;
        MemoryStream ms;
        unsecureResult = default(T);
        serializerSettings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat(_DateTypeFormat);

        serializer = new DataContractJsonSerializer(typeof(T));
        ms = new MemoryStream(Encoding.Unicode.GetBytes(json));

        unsecureResult = (T)serializer.ReadObject(ms);

        return unsecureResult;
    }

现在你的Datamodel将是

public class Result
{

    public string Coin { get; set; }
    public double LP { get; set; }
    public double PBV { get; set; }
    public bool MACD1M { get; set; }
    public bool MACD30M { get; set; }
    public bool MACD1H { get; set; }
    public bool MACD1D { get; set; }

}

public class RootObject
{
    public List<Result> results { get; set; }
}