Eric Legault
Eric Legault

Reputation: 5834

Can't deserialize Asana User data into C# class

I'm trying to deserialize the data I'm getting from the users/me call in the Asana API as per below, but the object is returning null for all properties in the jsonResponse var. The data is there - I can see it if I read it as pure text. I've also tried using [JsonProperty("id")] attributes instead of [DataMember] for use with a JsonSerializer instead of DataContractJsonSerializer, but I get an exception: "Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Data2'."

What am I doing wrong?

Note: I've been creating the classes using Xamasoft JSON Class Generator; see the class below the GetUser method.

        public AsanaObjects.Data2 GetUser()
    {
        AsanaObjects.Data2 result = null;
        string url = "https://app.asana.com/api/1.0/users/me";

        try
        {
            var uri = new Uri(url);
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CertificateCheck);
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
            //Must use Tls12 or else exception: "The underlying connection was closed: An unexpected error occurred on a send." InnerException = {"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var webRequest = (HttpWebRequest)WebRequest.Create(uri);
            webRequest.Timeout = 10000;
            webRequest.Method = "GET"; webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Accept = "application/json";
            //webRequest.UseDefaultCredentials = true; //doesn't seem to make a difference
            webRequest.Headers.Add("Authorization", "Bearer " + AsanaBroker.Properties.Settings.Default.AccessToken);

            using (var response = webRequest.GetResponse())
            {
                //using (var responseStream = ((HttpWebResponse)response).GetResponseStream())
                //{
                //    if (responseStream != null)
                //    {
                //        var reader = new System.IO.StreamReader(responseStream);
                //        string readerText = reader.ReadToEnd();
                //        //Example return data: {"data":{"id":12343281337970,"name":"Eric Legault","email":"[email protected]","photo":null,"workspaces":[{"id":1234250096894,"name":"foo"},{"id":123446170860,"name":"Personal Projects"},{"id":12345000597911,"name":"foo2"}]}}
                //    }
                //}
                using (var responseStream = ((HttpWebResponse)response).GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        try
                        {
                            AsanaObjects.Data2 jsonResponse = null;
                            var jsonSerializer = new DataContractJsonSerializer(typeof(AsanaObjects.Data2));
                            jsonResponse = jsonSerializer.ReadObject(responseStream) as AsanaObjects.Data2;

                            if (jsonResponse != null)
                            {
                                result = jsonResponse;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }

        return result;
    }

This is the class I'm trying to deserialize into (sorry for the initial unformatted part - not sure how to fix):

public partial class AsanaObjects { [DataContract] public class Workspace { [DataMember] public object id { get; set; }

        [DataMember]
        public string name { get; set; }
    }
}

public partial class AsanaObjects
{
    [DataContract]
    public class Data2
    {
        [DataMember]
        public long id { get; set; }

        [DataMember]
        public string name { get; set; }

        [DataMember]
        public string email { get; set; }

        [DataMember]
        public object photo { get; set; }

        [DataMember]
        public Workspace[] workspaces { get; set; }
    }
}

public partial class AsanaObjects
{
    [DataMember]
    public Data2[] data { get; set; }
}

Upvotes: 0

Views: 274

Answers (1)

Jonathan
Jonathan

Reputation: 5018

  1. data is not an array. In your sample it is a single object.
  2. You want to be deserializing at the root, AsanaObjects class, not one level down at the data class.
  3. I also had to throw a [DataContract] on the root AsanaObjects class

The following works and comes back with a full object:

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        const string Json = @"{""data"":{""id"":12343281337970,""name"":""Eric Legault"",""email"":""[email protected]"",""photo"":null,""workspaces"":[{""id"":1234250096894,""name"":""foo""},{""id"":123446170860,""name"":""Personal Projects""},{""id"":12345000597911,""name"":""foo2""}]}}";
        static void Main(string[] args)
        {
            var theReturn = DeserializeJson(Json);
        }

        private static  AsanaObjects DeserializeJson(string json) {
            var jsonSerializer = new DataContractJsonSerializer(typeof(AsanaObjects));
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));

            return jsonSerializer.ReadObject(stream) as AsanaObjects;
        }

        public partial class AsanaObjects
        {
            [DataContract]
            public class Workspace
            {
                [DataMember]
                public object id { get; set; }

                [DataMember]
                public string name { get; set; }
            }
        }

        public partial class AsanaObjects
        {
            [DataContract]
            public class Data2
            {
                [DataMember]
                public long id { get; set; }

                [DataMember]
                public string name { get; set; }

                [DataMember]
                public string email { get; set; }

                [DataMember]
                public object photo { get; set; }

                [DataMember]
                public Workspace[] workspaces { get; set; }
            }
        }

        [DataContract]
        public partial class AsanaObjects
        {
            [DataMember]
            public Data2 data { get; set; }
        }
    }
}

Upvotes: 1

Related Questions