10/29/2008

Использование JSON в Silverlight 2.0

Äëÿ ñåðèàëèçàöèè îáúåêòîâ â JSON ïðåäíàçíà÷åí DataContractJsonSerializer.
Íàïðèìåð, åñòü ñëåäóþùèé êëàññ:

public class DTO
{
    public Guid Id { get; set; }
    public string Value { get; set; } 

    public override string ToString()
    {
        return string.Concat("{Id='", this.Id, "', Value='", this.Value, "'}");
    }
}

ñîçäàåì ýêçåìïëÿð êëàññà:
var ct = new DTO() { Id = Guid.NewGuid(), Value = "hello" };

ñåðèàëèçîâàòü:
string json = JSON.Serialize(ct); 

ïîëó÷èì:
{"Id":"a90417e2-9689-4d80-8c34-b1faeb14823b","Value":"hello"}

äåñåðèàëèçîâàòü:
DTO dto = JSON.Deserialize<DTO>(json);

--

public static class JSON
{
    public static string Serialize(object value)
    {
        // ñîçäàòü ñåðèàëèçàòîð
        DataContractJsonSerializer js = new DataContractJsonSerializer(value.GetType());

        // ñîçäàòü ñòðèì; è çàïèñàòü â íåãî ðåçóëüòàò ñåðèàëèçàöèè
        MemoryStream ms = new MemoryStream();
        js.WriteObject(ms, value);

        // ïîëó÷èòü ñòðîêó èç ñòðèìà
        // v1:
        ms.Position = 0;
        using (StreamReader reader = new StreamReader(ms))
            return reader.ReadToEnd();

        // v2:
        // byte[] bytes = ms.ToArray();
        // return System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
    }

    public static T Deserialize<T>(string json)
    {
        // ñîçäàòü ñåðèàëèçàòîð
        DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
        // ñîçäàòü ñòðèì; è çàïèñàòü â íåãî ñòðîêó
        MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
        // äåñåðèàëèçîâàòü ...
        return (T)js.ReadObject(ms);
    }
}

 

0 Comments: