1

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

thankyou! Brian Rogers. it solve my issue. also one question can i parse that "0":{" so suppose if i want to add one more property string index to latestfile class can i parse that what need to be done?
dotnetfiddle.net/tC0Dws see this modification i can get index now i don't know if its best practice
@IkramKhan If you need the index, then yes, you'd need to get it from the KeyValuePair like you are doing. You can simplify it a bit using Linq (assuming you're comfortable with lambda expressions), but what you have will work fine.
well yes thats a great solution you have provided Thanks alot!. Actually theres another json response which have database ID for transactions just like here we have for index and we need to parse and insert that in db i will use similar technique.your solution save my time
1

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

2 Comments

nice but still not generic. and i guess its not possible for this type of json right meaning if more files are there i need to add more datamembers in Files right?
If you have an option to slightly modify your JSON and make it a list the solution will be way simpler. Something like this will do the trick: "Files": [{"FileURL":"htp:\/\/somedomain.com\/1.exe","FileVersion":"1"}, {"FileURL":"htp:\/\/somedomain.com\/1.exe","FileVersion":"2"}]. Then, in JsonResponse the Files property is actually a List<MyFile>.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.