简体   繁体   中英

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?

Firstly, you shouldn't be doing this in any normal sense ReadAsStringAsync().Result; . You are mixing async and synchronous code.

Secondly, your json doesn't match with the following

"detectedLanguage":{  
     "language":"en",
     "score":1.0
 },

and

public List<detectedLanguage> detectedLanguage { get; set; }

It should be

public detectedLanguage detectedLanguage { get; set; }

It's a json object not a list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM