首页 > 解决方案 > 为什么我的 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:值不能为空。参数名称:值

标签: c#jsonjsonconvert

解决方案


由于您已经完成了将结果转换为类似 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; }
    }
}

推荐阅读