【问题标题】:Convert JSON to list of objects将 JSON 转换为对象列表
【发布时间】:2019-04-07 05:25:12
【问题描述】:

我已经定义了一个像这样的Quote 类:

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

以下 JSON 由 Web API 休息端点返回,不包含显式 symbol 字段。符号是命名的对象,例如AAPL,GOOG,FB:

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

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

【问题讨论】:

  • 你的 json 中的 symbol 在哪里?
  • json 没有明确的“符号”字段,这是棘手的部分。
  • 那么这个symbol 来自哪里,在反序列化时将它分配给你的类中的Symbol 属性
  • Quote.Symbol 是股票代码,例如AAPLGOOGFB
  • 这个json对象是在哪里定义的?任何本地文件或者它只是一个字符串,而不是你想为这个 Quote 类转换为 json?

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


【解决方案1】:

处理 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();

输出:

【讨论】:

  • 这要简单得多。我想知道,是否适用于xml格式?
  • @its4zahoor,是的,如果您想将 xml 与 XDocument 一起使用。因为XDocument 支持 LINQ,并且使用 LINQ,您可以将结果展平为任何您想要的 :)
  • 啊,对了,我忘了动态 - 几年前使用的。但是 VS 给了我一个方法未找到 .Select 的错误 - 知道为什么吗?
  • @BaltoStar,将此命名空间添加到程序顶部 => using System.Linq;
  • @BaltoStar,发生了什么?对你起作用吗?如果是,请在答案左侧打勾,使其变为绿色:)
【解决方案2】:

您可以自定义 JsonConverter 以将此 JSON 结构转换为您想要的 List&lt;Quote&gt; 格式。

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();
    }
}

然后像这样使用它:

var quotes = JsonConvert.DeserializeObject(json, new QuoteListConverter());

工作演示:https://dotnetfiddle.net/kcU8DO

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多