How to create the object according to json string,it shows below, it is a google translate's api, and how to deserialize it in c#

StackOverflow https://stackoverflow.com/questions/23451447

Question

This is the json string:

 {
     "data": {
      "translations": [
       {
        "translatedText": "trabajo"
       }
      ]
     }
    }

I think it is the way, but it doesn't work:

           [DataContract]
            class Result
            {
                [DataMember]
                public Data data { get; set; }

            }

            [DataContract]
            class Data 
            {
                [DataMember]
                public Translations translations { get; set; }  

            }

            [DataContract]
            class Translations
            {
                [DataMember]
                public string translatedText  { get; set; }

            }

Deserilazing using DataContractJsonSerializer, it gives an excepcion: Additional information: Unable to cast object of type 'System.Collections.Generic.List1[System.Object]' to type 'System.Collections.Generic.Dictionary2[System.String,System.Object]'.

 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Result));
 MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
 Result obj = (Result)ser.ReadObject(stream);
Was it helpful?

Solution 2

transations is an array basically so you need to have an list of Translations as shown below.

[DataContract]
class Data 
{
    [DataMember]
    public List<Translations> translations { get; set; }  
}

OTHER TIPS

Rashmin is right. You can use http://json2csharp.com/ as a starting point in the future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top