0

I have an inconsistent JSON file, that was likely generated by hand. Here's a truncated example:

[
    {
        "Generic Name": "Lurasidone",
        "Brand Name": ["Latuda"]
    }
    {
        "Generic Name": "Lisdexamfetamine",
        "Brand Name": "Vyvanse"
    }
]

Since "Brand Name" is [] for one, and just a regular string for another, how do I take care of this in .NET?

public class Drug
{
    [JsonProperty("Generic Name")]
    public string GenericName {get; set;}

    [JsonProperty("Brand Name")]
    public string[] BrandName {get; set;}
}

List<Drug> a = JsonConvert.DeserializeObject<List<Drug>>(
    File.ReadAllText("d.json"));

Results in the error:

Error converting value "Vyvanse" to type 'System.String[]'. Path '[1].Brand Name', line 20, position 26.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
BBH1023
  • 515
  • 2
  • 7
  • 18
  • 2
    You'll have to use a [custom converter](http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConverter.htm) and perhaps use a try-catch to parse it one way and if it fails, parse it the other way. The exact implementation can go different routes. Nasty JSON creates nasty code. – Jeroen Vannevel Aug 25 '14 at 14:59
  • The `BrandName` on the second object is not a `array`. – Felipe Oriani Aug 25 '14 at 15:01
  • 1
    @FelipeOriani that was the question – BBH1023 Aug 25 '14 at 15:02
  • the answer at http://stackoverflow.com/questions/22052430/how-to-handle-json-that-returns-both-a-string-and-a-string-array answered my question – BBH1023 Aug 25 '14 at 15:16

0 Answers0