Ikram Khan
Ikram Khan

Reputation: 73

Parse Json response and create List of files

how can i parse this json response and create c# object

{"Response":"valid","Files":{"0":{"FileURL":"htp:\/\/somedomain.com\/1.exe","FileVersion":1},"1":{"FileURL":"htp:\/\/somedomain.com\/1.exe","FileVersion":2}}}

i have c# class

public class Files
{
public string fileURL;
public string fileVersion;
}


WebClient wc=new WebClient();
string code=wc.DownloadString("http://somedomain.com/GetLatestFiles.php");
List<Files> f=ParseJson(code);

how can i parse this json please help. I need to implement ParseJson which will return files list or can i deserialize this response to c# class?

Thankyou

Edit implemented some solution but its very slow?

public class LatestFile
    {
        public string fileURL;
        public string fileVersion;
    }


private List<LatestFile> ParseJson(string code)
        {
            List<LatestFile> files = new List<LatestFile>();

            dynamic jObj = JsonConvert.DeserializeObject(code);

            foreach (var child in jObj.Files.Children())
            {
                string index = child.Name;
                string url = child.First.FileURL.Value;
                string version = child.First.FileVersion.Value.ToString();
                LatestFile f = new LatestFile();
                f.fileURL = url;
                f.fileVersion = version;
                files.Add(f);

            }
            return files;
        }

Based on @Brian Rogers answer below i am able to implement the generic solution working fast and efficiently.Thanks

https://dotnetfiddle.net/tC0Dws

Upvotes: 1

Views: 126

Answers (2)

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

According to the JSON you provided you have three different objects there. First with Response and Files fields. Second - it looks like it's intended to be a collection but with current implementation it's an object - with fields 0 and 1. And third one with fields FileURL and FileVersion.

You can use DataContractJsonSerializer which is available starting from .Net 4.5. It's in System.Runtime.Serialization.Json namespace.

To parse your JSON you need following data structure:

[DataContract]
public class JsonResponse
{
    [DataMember(Name = "Response")]
    public string Response { get; set; }

    [DataMember(Name = "Files")]
    public Files Files { get; set; }
}
[DataContract]
public class Files
{
    [DataMember(Name = "0")]
    public MyFile Frst { get; set; }

    [DataMember(Name = "1")]
    public MyFile Scnd { get; set; }
}

[DataContract]
public class MyFile
{
    [DataMember(Name = "FileURL")]
    public string FileURL { get; set; }

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

To make testing easier I'm using your sample as a string but you can easily use URL or a Stream:

static string json = @"
{
    ""Response"":""valid"",
    ""Files"":
    {
        ""0"":
        {
            ""FileURL"":""htp:\/\/somedomain.com\/1.exe"",""FileVersion"":""1""
        },
        ""1"":
        {
            ""FileURL"":""htp:\/\/somedomain.com\/1.exe"",""FileVersion"":""2""
        }
    }
}";

static void Main(string[] args)
{
    var serializer = new DataContractJsonSerializer(typeof(JsonResponse));

    DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(JsonResponse));
    using (MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(json)))
    {
        JsonResponse response = (JsonResponse)js.ReadObject(ms);
    }
}

And that's the result:

enter image description here

Upvotes: 1

Brian Rogers
Brian Rogers

Reputation: 129687

Try defining your classes like this:

public class RootObject
{
    public string Response { get; set; }
    public Dictionary<string, LatestFile> Files { get; set; }
}

public class LatestFile
{
    public string FileURL { get; set; }
    public string FileVersion { get; set; }
}

And make your helper method like this:

private List<LatestFile> ParseJson(string json)
{
    RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
    return obj.Files.Values.ToList();
}

Fiddle: https://dotnetfiddle.net/vpre5H

Upvotes: 2

Related Questions