Search code examples
c#jsonjavascriptserializer

Reading data from json array


My json format is like -

{
 "data": {
  "translations": [
   {
    "translatedText": "مرحبا"
   }
  ]
 }
}

i want to read translated text value without using json.net . but it always returns null value.

 JavaScriptSerializer ser = new JavaScriptSerializer();
            nameList myNames = ser.Deserialize<nameList>(json);

Solution

  • public class nameList { public name[] Translator { get; set; } }

    That's an incorrect class to map the Json to.


    Try these classes to deserialize the Json and it will work perfectly fine:

    public class Translation
    {
        public string translatedText { get; set; }
    }
    
    public class Data
    {
        public List<Translation> translations { get; set; }
    }
    
    public class nameList
    {
        public Data data { get; set; }
    }
    

    Example reaching for the translatedText property:

    var text = myNames.data.translations[0].translatedText;