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.

4
  • 2
    You'll have to use a custom converter 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. Commented Aug 25, 2014 at 14:59
  • The BrandName on the second object is not a array. Commented Aug 25, 2014 at 15:01
  • 1
    @FelipeOriani that was the question Commented Aug 25, 2014 at 15:02
  • the answer at stackoverflow.com/questions/22052430/… answered my question Commented Aug 25, 2014 at 15:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.