Reading JSON files with C# and JSON.net

冷暖自知 提交于 2020-01-12 05:45:09

问题


Im having some trouble to understand how to use JSON.net to read a json file.

The file is looking like this:

"version": {   
    "files": [
        {
            "url": "http://www.url.com/",
            "name": "someName"
        },
        { 
            "name": "someOtherName"
            "url": "http://www.url.com/"
            "clientreq": true
        }, ....

I really do not have much idea how i can read this file .. What i need to do is to read the lines and download the file via the "url".. I know how to download files and so on, but i dont know how i can use JSON.net to read the json file and loop through each section, and download the file..

Can you assist ?


回答1:


The easiest way is to deserialize your json into a dynamic object like this

Then you can access its properties an loop for getting the urls

dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

var urls = new List<string>();

foreach(var file in result.version.files)
{
    urls.Add(file.url); 
}



回答2:


http://json2csharp.com/ helps you create C# classes based on your JSON data type. Once you have your classes to match your data, you can deserialize with Json.NET and then work with your data:

var myMessage = JsonConvert.DeserializeObject<MyMessage>(myString);
foreach (var file in myMessage.Version.Files)
{
    // download file.Url
}

Or you can access it as a dynamic object:

dynamic myMessage = JsonConvert.DeserializeObject(myString);
foreach (var file in myMessage.version.files)
{
    // download file.url
}

If you use classes, they might be:

public class File
{
    public Uri Url { get; set; }
    public string Name { get; set; }
    public bool? ClientReq { get; set; }
}

public class Version
{
    public IList<File> Files { get; set; }
}

public class MyMessage
{
    public Version Version { get; set; }
}

(note that Json.Net is smart enough to map properties where the case is different, and turn the URLs into Uri objects) It works when the string is like:

string myString = @"{""version"": {   
    ""files"": [
        {
            ""url"": ""http://www.url.com/"",
            ""name"": ""someName""
        },
        { 
            ""name"": ""someOtherName"",
            ""url"": ""http://www.url.com/"",
            ""clientreq"": true
        }]}}";


来源:https://stackoverflow.com/questions/19596135/reading-json-files-with-c-sharp-and-json-net

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