Search code examples
c#asp.net-web-apijson.net

Unable to cast object of type 'System.Object[]' to type my class C#


I am getting the data from one of my APIs for language conversion

here is my query

var jsonResponse = response.Content.ReadAsStringAsync().Result;

the following is my sample data

[{"detectedLanguage":{"language":"en","score":1.0},"translations":[{"text":"All","to":"en"},{"text":"सभी","to":"hi"}]}]

now I want to convert the data in List

so I created some class as per my data

    public class translations
    {
        public string text { get; set; }
        public string to { get; set; }
    }

    public class detectedLanguage
    {
        public string language { get; set; }
        public float score { get; set; }
    }

    public class TranslatedString
    {
        public List<detectedLanguage> detectedLanguage { get; set; }
        public List<translations> translations { get; set; }
    }

and use newtonsoft.Json to convert this data into list like the following

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
TranslatedString routes_list = (TranslatedString)json_serializer.DeserializeObject(jsonResponse);

but I am getting the error like the following

Unable to cast object of type 'System.Object[]' to type 'Avalon.TranslatedString'.

what can be done to fix this?


Solution

  • You can generate classes from JSON using this website - Here

    In your case Classes will be -

    public class DetectedLanguage
    {
        public string language { get; set; }
        public double score { get; set; }
    }
    
    public class Translation
    {
        public string text { get; set; }
        public string to { get; set; }
    }
    
    public class RootObject
    {
        public DetectedLanguage detectedLanguage { get; set; }
        public List<Translation> translations { get; set; }
    }
    

    and code to Deserialize will be -

    var data = JsonConvert.DeserializeObject<List<RootObject>>(jsonString);