Why is my JsonConvert not converting correctly

131 views Asked by At

I am getting data from an API and want to convert it to a List of Objects

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

Example of data return:

{
 "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,,",
 ]

The converted model I Example I am converting to:

public class ConvertedModel {
    public string Name { get; set; }
    public string Subject { get; set; }
    public decimal Score { get; set; }
    public decimal PrevScore { get; set; }
}

The Exception message:

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

The Inner Exception:

ArgumentNullException: Value cannot be null. Parameter name: value

1

There are 1 answers

0
Robert McKee On BEST ANSWER

Since you've already done the work to get the result into a CSV-like format, I would just continue down that route. Note that I am including the nuget packages Newtonsoft.Json and 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; }
    }
}