Search code examples
c#asana

Storing only task id in an array


I am creating a program that will automate some functions with Asana for my workplace but am a bit stuck. I am able to submit multiple tasks to a workspace and retrieve the task ID's of each but was wondering how to take only the ID portion of the response and store it into an array or list in C#.

The response from the GET on /tasks?workspace=<workspace-id>&assignee=me is:

{"data":[{"id":2177890732156,"name":"<name of my task>"}]}

I want to store the id number(s) from all my tasks into an array so I can perform an addProject PUT to each of them.

I am using a serializer to put data elements into the proper dictionary for POSTing but am wondering if there is a way to reverse it and parse only the int portion of the response, store it in an array and call it back up.

The serializer code is as follows:

public static string GetJsonByObject(object _object)
    {
        /// Serialize to JSON
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(_object.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, _object);
        return Encoding.Default.GetString(ms.ToArray());
    }

and I have been storing my requests in a byte array as follows:

string content;

content = GetJsonByObject(t);
bArrContent = Encoding.UTF8.GetBytes(content);
            request.GetRequestStream().Write(bArrContent, 0, bArrContent.Length);
            request.GetRequestStream().Close();

Solution

  • It is certainly possible to use some Regex-fu to parse out the ID fields and store them. However, that's kindof nasty - Structured data formats like JSON and XML exist for the purpose of having someone else's parsing library do the dirty work for you.

    So, suggestion 1: Use JSON.Net instead of DataContractSerializer. It sucks less.

    which leads to suggestion 2: Use a library to deserialize your data cleanly, then use Linq to grab the ID elements:

    JObject jobj = JObject.Parse(serializedData);
    UInt64[] idArr = ((JArray)jobj["data"]).Select(jItem => UInt64.Parse((string)((JObject)jItem["id"]))).ToArray();
    

    Now you should have the list of IDs as an array in idArr.