c# iterate through json

浪尽此生 提交于 2019-12-13 21:38:57

问题


Currently I am working on a soundcloud downloader in C#. With the help of the SoundCloud API I get a JSON string of a playlist, which includes a lot of information of the tracks:

http://pastebin.com/HfrjqyJE

I tried it with:

JObject results = JObject.Parse(e.Result);
foreach (var result in results["tracks"])
{
     string streamUrl = (string)result["stream_url"];
     string title = (string)result["title"];
}

it worked but it needs about 20 secs to iterate through a playlist with only 2 tracks. Is there a way to make this iteration process faster?


回答1:


You could try using Newtonsoft JSON Deserializer.

For your case you could do something like this:

  1. Create a Track class with needed properties

  2. Apply DeserializeObject

    Track jsonObject = JsonConvert.DeserializeObject<Track >(json);
    
  3. Iterate over jsonObject




回答2:


Perhaps looping over the properties using JProperty, performs better?

    string json = "{a: 10, b: 'aaaaaa', c: 1502}";

    JObject parsedJson = JObject.Parse(json);
    foreach (JProperty property in parsedJson.Properties())
    {
        Console.WriteLine(string.Format("Name: [{0}], Value: [{1}].", property.Name, property.Value));
    }


来源:https://stackoverflow.com/questions/31539656/c-sharp-iterate-through-json

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