c# 4.0 - Parse Json response and create List of files -
how can parse json response , 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 parse json please help. need implement parsejson return files list or can deserialize response c# class?
thankyou
edit implemented solution 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 able implement generic solution working fast , efficiently.thanks
try defining classes 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 helper method this:
private list<latestfile> parsejson(string json) { rootobject obj = jsonconvert.deserializeobject<rootobject>(json); return obj.files.values.tolist(); }
fiddle: https://dotnetfiddle.net/vpre5h
Comments
Post a Comment