0

my jsonResult is always have 1+ Invoice (class), If it has 1 Invoice it gives error.

How can I change fromJson <List to have a only 1 class.

If jsonResult has more than 1 Invoice -- no error If jsonResult = 1 Invoice gives error. How can I fix it.

string jsonResult = (await GenericHttpClient.ExecuteAsync(requestModel)).Content;

 try
 {                

  return jsonResult.FromJson<List<Invoice>>();

 }
bestpro
  • 5
  • 3
  • check this https://stackoverflow.com/questions/14977848/how-to-make-sure-that-string-is-valid-json-using-json-net will help, but you can use simple solution : check if ``jsonResult`` is not start with `[` and update the json like : `jsonResult = $"[{jsonResult }]"` – Mohammed Sajid Apr 19 '21 at 01:32
  • What JsonDeserialiser are you using? Json.NET or System.Text.Json? – tymtam Apr 19 '21 at 02:35

1 Answers1

1

Here's a version for System.Text.Json:

public static List<int> GetValues(string json)
{
    using JsonDocument doc = JsonDocument.Parse(json);
    if (doc.RootElement.ValueKind == JsonValueKind.Array)
    {
        return JsonSerializer.Deserialize<List<int>>(json);
    }
    else
    {
        return new List<int>(){ JsonSerializer.Deserialize<int>(json) };
    }
}
var a = GetValues("[1,2,3]"); // List with 3 elements: 1,2,3
var b = GetValues("1");       // List with 1 element: 1
tymtam
  • 31,798
  • 8
  • 86
  • 126