c# - 为什么我的 JsonConvert 不能正确转换
问题描述
我从 API 获取数据并希望将其转换为对象列表
// Get the data
var searchResult = GetResults();
string[] data = (string[]) searchResult.Data;
string headers = searchResult.Headers;
// Combine the data into CSVish format
var sb = new StringBuilder();
sb.AppendLine(headers);
foreach(var recordString in data){
sb.AppendLine(recordString);
}
// Convert to a new a JsonFormat
/* This is where the issue is. I get the an exeption */
var convertedData = JsonConvert.DeserializeObject<List<ConvertedModel>>(sb.ToString());
数据返回示例:
{
"Headers": "Name, subject, score, prevScore"
"Data":[
"Jhon,Math,24.54, 30",
"Jhon,English,,28.23",
"Jhon,Art,13.53,12",
"Joe,Math,27.01,",
"Joe,English,,",
]
转换后的模型 I 示例我正在转换为:
public class ConvertedModel {
public string Name { get; set; }
public string Subject { get; set; }
public decimal Score { get; set; }
public decimal PrevScore { get; set; }
}
异常消息:
System.Reflection.TargetInvocationException: '调用的目标已抛出异常。'
内部异常:
ArgumentNullException:值不能为空。参数名称:值
解决方案
由于您已经完成了将结果转换为类似 CSV 格式的工作,因此我将继续沿着这条路线走下去。请注意,我包括了 nuget 包 Newtonsoft.Json 和 FileHelpers:
using System;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using FileHelpers;
public class Program
{
public static void Main()
{
/*var searchResult = GetResults();
string[] data = (string[]) searchResult.Data;
string headers = searchResult.Headers;
// Combine the data into CSVish format
var sb = new StringBuilder();
sb.AppendLine(headers);
foreach(var recordString in data){
sb.AppendLine(recordString);
}*/
var sb = new StringBuilder();
sb.Append(@"Name, subject, score, prevScore
Jhon,Math,24.54, 30
Jhon,English,,28.23
Jhon,Art,13.53,12
Joe,Math,27.01,
Joe,English,,");
// Convert to a new a JsonFormat
/* This is where the issue is. I get the an exeption */
//var convertedData = JsonConvert.DeserializeObject<List<ConvertedModel>>(sb.ToString());
var engine = new FileHelperEngine<ConvertedModel>();
var convertedData = engine.ReadString(sb.ToString());
}
[DelimitedRecord(",")]
[IgnoreFirst(1)]
public class ConvertedModel {
public string Name { get; set; }
public string Subject { get; set; }
[FieldOptional]
public decimal? Score { get; set; }
[FieldOptional]
public decimal? PrevScore { get; set; }
}
}
推荐阅读
- kotlin - 如何进行 kotlin mediaPlayer 随机播放
- sql - SQL - 为表中的每个货币代码(在两个定义的日期之间)创建一个具有唯一日期和货币记录的表
- spring - spring 如何跟踪交易结果?
- html - Outlook 通过电子邮件发送 TD 单元格中的额外空间
- graph - 用于连接本体的 NLP 和/或图挖掘技术?
- python - 在 Pyspark 中将字符串转换为时间戳对象
- windows-7 - 客户端应用程序发送用户名,SQL Server 2019 将其转换为 Windows 身份验证并引发错误
- cassandra - 修复 Cassandra 中的 system_auth 密钥空间
- php - 在类别或标签页面上找不到菜单项
- laravel - Laravel Collection sortBy函数的问题