1

Hi I have a response from the web service and i would like to have a single url from the response. My response is in the below format.

[{"cdn_streaming_uri": "9e849cfbb2e157-22558a0600b387d0abe240fe5.r73.stream..rackcdn.com", "name": "test1", "cdn_ios_uri": "d3d4c27-22558a0600b387d0abc071d0ae240kcdn.com", "cdn_ssl_uri": "https://990fea26e-22558a0600b387d0abc071d0ae240fe5.ssl.cdn.com", "cdn_enabled": false, "ttl": 259200, "log_retention": false, "cdn_uri": "99b56a009-22558a0600b3c071d0ae240fe5.r73.n.com"}, {"cdn_streaming_uri": "74ec8c-d5edc6cad91792413b1b134fde.r46.stcdn.com", "name": "test2", "cdn_ios_uri": "d05437e44-d5edc61792413b1b134fde.iosr.cdn.com", "cdn_ssl_uri": "https://a1c2ebbf5-d5edc6cd91792413b1b134fde.scdn.com", "cdn_enabled": false, "ttl": 259200, "log_retention": false, "cdn_uri": "72ffd-d5edc6ca16852413b1b134fde.cdn.com"}, {"cdn_streaming_uri": "93665b76-550971032c2a22cdn.com", "name": "test3", "cdn_ios_uri": "ca6b-550971032c2fbf19452d6a.iosr.cf2.rackcdn.com", "cdn_ssl_uri": "https://c7c39-550971032cbf19452d6cdn.com", "cdn_enabled": true, "ttl": 86400, "log_retention": true, "cdn_uri": "68fc6d831a94-550971032c252d6a.r3cdn.com"}]

I need to the "cdn_streaming_uri" for the name "test3".

You can view the JSON parser in http://json.parser.online.fr/ How do i parse it?

Here is my code:

public static object getTokenResponse(String PrivateURL, string ResponseType)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PrivateURL +"?format=JSON");
    request.Method = "GET";
    request.Headers.Add("X-Auth-Token", id);
    //request.ContentType = "application/XML";

    HttpWebResponse resp1;
    try
    {
        resp1 = (HttpWebResponse)request.GetResponse();
    }
    catch (Exception exp)
    {
        string[] st = new string[0];
        return st;
    }


    StreamReader reader = new StreamReader(resp1.GetResponseStream());
    string  secondresponse = reader.ReadToEnd();
    Console.WriteLine(secondresponse);
    reader.Close();

    JavaScriptSerializer json_serializer = new JavaScriptSerializer();
    object obj1 = json_serializer.DeserializeObject(secondresponse);
}

I could see the response in obj1.

3
  • What have you tried? Did you make a class structure of the JSON format that you are getting? What is exactly your problem with getting "test3"? Oct 29, 2014 at 7:29
  • You haven't shown what you have already tried to achieve what you need. Show us your code where you parse the JSON and where you are struggling with. Oct 29, 2014 at 7:33
  • I would recommend for you to read up more about JSON here, here and here. After all that you will better understand how to work with the data you got and the answers below. Oct 29, 2014 at 7:49

2 Answers 2

9

The best approach, I think, is to create class which will represent your response. The easiest way is to use Visual Studio's EDIT -> Paste Special -> Paste JSON As Classes option:

enter image description here

You just copy your response and paste it as JSON classes. Visual studio will generate model for you. In this particular case the result will be:

namespace ConsoleApplication91
{
    public class Rootobject
    {
        public Class1[] Property1 { get; set; }
    }

    public class Class1
    {
        public string cdn_streaming_uri { get; set; }
        public string name { get; set; }
        public string cdn_ios_uri { get; set; }
        public string cdn_ssl_uri { get; set; }
        public bool cdn_enabled { get; set; }
        public int ttl { get; set; }
        public bool log_retention { get; set; }
        public string cdn_uri { get; set; }
    }
}

which, of course, does not look very nice, but you're always welcome to refactor this code. When you have your model you download your response, parse it and get what you need using linq, for example:

using (var client = new WebClient())
{
    var url = "your service url";
    var serializer = new JavaScriptSerializer();

    // Response in JSON format
    var respJson = client.DownloadString(url);

    // Deserialized response
    var resp = serializer.Deserialize<Rootobject>(respJson);

    // Your requested result
    var result = resp.Property1.FirstOrDefault(o => o.name == "test3").cdn_streaming_uri;
}

EDITS:

After refactoring (using DataMember attributes and removing redundant model objects) you can have the following model:

[DataContract]
public class Model
{
    [DataMember(Name = "cdn_streaming_uri")]
    public string CdnStreamingUri { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

    [DataMember(Name = "cdn_ios_uri")]
    public string CdnIosUri { get; set; }

    [DataMember(Name = "cdn_ssl_uri")]
    public string CdnSslUri { get; set; }

    [DataMember(Name = "cdn_enabled")]
    public bool CdnEnabled { get; set; }

    [DataMember(Name = "ttl")]
    public int Ttl { get; set; }

    [DataMember(Name = "log_retention")]
    public bool LogRetention { get; set; }

    [DataMember(Name = "cdn_uri")]
    public string CdnUri { get; set; }
}

After some research I've figured out that JavascriptSerializer is a little deprecated and it does not support any kind of DataMemberAttributes. So I would recommend to use DataContractJsonSerializer. It is little messier than JavascriptSerializer but I think it's fine. If you do not care about any code conventions you can peacefully use the firs provided option (with JavaScriptSerializer and no DataMember attributes). And do not forget to update result query:

using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(respJson)))
{
    var serializer = new DataContractJsonSerializer(typeof(Model[]));
    var resp = serializer.ReadObject(ms) as Model[];

    var result = resp.FirstOrDefault(o => o.Name == "test3").CdnStreamingUri;
}

But, also, if you don't want to use linq (which I'm still strongly recommend) you can create some function which will find the CdnStreamingUri you need:

public static class Extensions
{
    public static string GetCdnStreamingUriFor(this Model[] input, string name)
    {
        foreach (var model in input)
        {
            if (model.Name == name)
                return model.CdnStreamingUri;
        }

        return string.Empty;
    }
}

And your result query will look like:

var result = resp.GetCdnStreamingUriFor("test3");

P.S. Full list of all used namespaces:

using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Runtime.Serialization;
4
  • Well, linq is very powerful stuff, you should not ignore it. See my edits: your obj is an array of Model class instances and if you don't want to use linq you have to loop through it's elements, check the item name and if .Name == "test3" return .CdnStreamingUri .
    – Dmytro
    Oct 29, 2014 at 8:17
  • @Manikanta, I've added some updated with full list of namespaces.
    – Dmytro
    Oct 29, 2014 at 8:58
  • @MemetOlsen, as you can see from screen shot it is also applicable for xml data format.
    – Dmytro
    Oct 29, 2014 at 9:04
  • 1
    @Manikanta, here's the solution
    – Dmytro
    Oct 29, 2014 at 20:37
1

I recommend you to generate class for that json, like the following (http://json2csharp.com/ ):

public class RootObject
{
    public string cdn_streaming_uri { get; set; }
    public string name { get; set; }
    public string cdn_ios_uri { get; set; }
    public string cdn_ssl_uri { get; set; }
    public bool cdn_enabled { get; set; }
    public int ttl { get; set; }
    public bool log_retention { get; set; }
    public string cdn_uri { get; set; }
}

After that you can deserialize strongly typed object http://msdn.microsoft.com/en-us/library/bb355316(v=vs.110).aspx

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.