locked
how to pass json object to webclient RRS feed

  • Question

  • hi there,

    I was having an issue with my development here. We are developing a windows 7.1 app which consumes WebAPI based web service. I have some GET calls which passes a Json object.

    How to get the response? It always throws error.

    please respond to dennisjohn@gmail.com

    Tuesday, August 13, 2013 6:33 AM

Answers

  • Hi dennis,

    Here is a simple helper class that uses the DataContractJsonSerializer class to serialize / deserialize object to and from JSON.

    public static class JsonHelper
    {
        public static string ToJson<T>(T instance)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var tempStream = new MemoryStream())
            {
                serializer.WriteObject(tempStream, instance);
                return Encoding.Default.GetString(tempStream.ToArray());
            }
        }
    
        public static T FromJson<T>(string json)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var tempStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                return (T)serializer.ReadObject(tempStream);
            }
        }
    }
    
    

    Best Regards

    Jambor yao
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, August 14, 2013 8:51 AM
    Moderator