Reputation: 13
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?
Upvotes: 1
Views: 1657
Reputation: 81523
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.
Upvotes: 1
Reputation: 716
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);
Upvotes: 1