Deserialization of JSON object by using DataContractJsonSerializer in C#

stvn03 picture stvn03 · Jul 1, 2013 · Viewed 22.1k times · Source

I'm sure this question has been asked over and over again, but for some reason, I still can't manage to get this to work.

I want to deserialize a JSON object that contains a single member; a string array:

[{"idTercero":"cod_Tercero"}]

This is the class that I'm trying to deserialize into:

[DataContract]
public class rptaOk
{
    [DataMember]
    public string idTercero { get; set; }

    public rptaOk() { }

    public rptaOk(string idTercero)
    {
        this.idTercero = idTercero;
    }
}

This is the method that I try to deserialize:

public T Deserialise<T>(string json)
    {
        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            T result = (T)deserializer.ReadObject(stream);
            return result;
        }
    }

And so I try to fill the object:

rptaOk deserializedRpta = deserializarOk(rpta);

But for some reason, this returns ""

MessageBox.Show(deserializedRpta.idTercero);

Answer

Perpetualcoder picture Perpetualcoder · Jul 1, 2013

Without any dependencies outside of the .net framework, you could do it this way

[DataContract(Name="rptaOk")]
public class RptaOk
{
    [DataMember(Name="idTercero")]
    public string IdTercero { get; set; }
}

[CollectionDataContract(Name="rptaOkList")]
public class RptaOkList : List<RptaOk>{}

var stream = new StreamReader(yourJsonObjectInStreamFormat);
var serializer = new DataContractSerializer(typeof(RptaOkList));
var result = (RptOkList) serializer.ReadObject(stream);