将JSON转换为对象列表

时间:2019-04-07 05:25:12

标签: c# json json.net data-conversion

我已经定义了一个Quote类,如下所示:

public class Quote
{
    public double Price { get; set; }
    public string Symbol { get; set; }
}

以下JSON由Web API剩余端点返回,并且不包含显式的symbol字段。这些符号是命名对象,例如AAPLGOOGFB

{                       
    "AAPL": {           
        "price": 205    
    },                  
    "GOOG": {           
        "price": 1230.38
    },                  
    "FB": {             
        "price": 178.41 
    }                   
}    

将此JSON转换为List<Quote>的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

一种处理json棘手部分的简单方法

1)将您的json反序列化为Dictionary<string, dynamic>

2)然后将字典结果展平为List<Quote>

string json = File.ReadAllText(@"Path to your json");

List<Quote> quotes = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json)
    .Select(x => new Quote
    {
        Symbol = x.Key,
        Price = x.Value.price    //<= x.Value is dynamic type so you can access your key with dot(.) separator
    })
    .ToList();


//-------------Print the result to Console-------------

Console.WriteLine("Symbol\tPrice");
Console.WriteLine("----------------------");
foreach (var quote in quotes)
{
    Console.WriteLine(quote.Symbol +"\t" + quote.Price);
}

替代:

您可以使用JToken代替dynamic

List<Quote> quotes = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(json)
    .Select(x => new Quote
    {
        Symbol = x.Key,
        Price = Convert.ToDouble(x.Value["price"])
    })
    .ToList();

输出:

enter image description here

答案 1 :(得分:2)

您可以进行自定义JsonConverter,以将该JSON结构转换为所需的if __name__ == '__main__': #create table db.create_all() db.init_app(app) # remember to turn app debug by setting it to false in production app.run(debug=True) 格式。

List<Quote>

然后像这样使用它:

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class QuoteListConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<Quote>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject obj = JObject.Load(reader);
        return obj.Properties()
                  .Select(p => new Quote
                  {
                      Symbol = p.Name,
                      Price = p.Value["price"].ToObject<double>()
                  })
                  .ToList();
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

正在运行的演示:https://dotnetfiddle.net/kcU8DO