无密钥反序列化JSON

时间:2017-10-01 19:27:20

标签: c# json serialization

如何反序列化?

{"bids":[[15575.35,2.44],[15567.47,2.06],[15567.07,4.68],[15563,0.11240254]],
"asks":[[16493.08,3.22487788],[16498.86,0.01864],[16550,0.0756622],[16650,0.00182419]]}

我的代码:

        string remoteUri = "https://bitbay.net/API/Public/BTCPLN/orderbook.json";
        WebClient myWebClient = new WebClient();
        var json = myWebClient.DownloadString(remoteUri);
        JavaScriptSerializer js = new JavaScriptSerializer();
        var test = js.Deserialize<OrderBook>(json);


    class OrderBook
{
    public List<Order> bids { get; set; }
    public List<Order> asks { get; set; }
}

   public class Order  
{
  public Double rate { get; set; }
  public Double amount { get; set; }

}

我有这个错误:     System.Web.Extensions.dll中出现未处理的“System.InvalidOperationException”类型异常

其他信息:对于数组的反序列化,不支持类型“GetValue.Class.Order”。

1 个答案:

答案 0 :(得分:1)

看一下这个网站quicktype.io,它将为您提供以下完整示例

namespace QuickType
{
    using System;
    using System.Net;
    using System.Collections.Generic;

    using Newtonsoft.Json;

    public partial class Quote
    {
        [JsonProperty("asks")]
        public List<List<double>> Asks { get; set; }

        [JsonProperty("bids")]
        public List<List<double>> Bids { get; set; }
    }

    public partial class Quote
    {
        public static Quote FromJson(string json) =>
            JsonConvert.DeserializeObject<Quote>(json, Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Quote self) =>
            JsonConvert.SerializeObject(self, Converter.Settings);
    }

    public class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
        };
    }
}

反序列化您的Json只需致电

 var remoteUri = "https://bitbay.net/API/Public/BTCPLN/orderbook.json";
 var myWebClient = new WebClient();
 var json = myWebClient.DownloadString(remoteUri);            
 var quote = Quote.FromJson(json);