Storing only task id in an array

三世轮回 提交于 2019-12-13 15:43:20

问题


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();

回答1:


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.



来源:https://stackoverflow.com/questions/12923034/storing-only-task-id-in-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!