从C#文件中反序列化Json [英] Deserialize Json from file in C#

查看:91
本文介绍了从C#文件中反序列化Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将Json加载到字符串中,将其反序列化为动态字符串,对它进行遍历,然后添加到其中包含ResFiles的列表中.

Loaded the Json to a string, deserialized it into a dynamic, ran a foreach through it, and added to a List with ResFiles in it.

static void loadJson()
{
    List<ResFile> fileList = new List<ResFile>();
    string jsonString = File.ReadAllText(jsonPath);
    dynamic files = JsonConvert.DeserializeObject(jsonString);

    foreach (var f in files.objects)
        fileList.Add(new ResFile(f.Name, f.Value.hash.ToString(), (int)f.Value.size.Value));
}



我正在尝试使用Newtonsoft的Json库反序列化C#中的某些Json文件.
这些文件以其哈希命名,而不是真实的文件名,我想将它们重命名为适当的名称,如下所示:
10a54fc66c8f479bb65c8d39c3b62265ac82e742 >> file_1.ext


I'm trying to deserialize some Json file in C# with Newtonsoft's Json library.
The files are named after it's hash, not the real file name and I want to rename them back to the proper names, so like this:
10a54fc66c8f479bb65c8d39c3b62265ac82e742 >> file_1.ext

Json文件:

{
  "files": {
    "file_1.ext": {
      "hash": "10a54fc66c8f479bb65c8d39c3b62265ac82e742",
      "size": 8112
    },
    "file_2.ext": {
      "hash": "14cfb2f24e7d91dbc22a2a0e3b880d9829320243",
      "size": 7347
    },
    "file_3.ext": {
      "hash": "bf7fadaf64945f6b31c803d086ac6a652aabef9b",
      "size": 3838
    },
    "file_4.ext": {
      "hash": "48f7e1bb098abd36b9760cca27b9d4391a23de26",
      "size": 6905
    }
  }
}

我已经尝试过反序列化:

I've tried deserialize with this:

static void loadJson()
{
    using (StreamReader reader = new StreamReader(jsonPath))
    {
        string json = reader.ReadToEnd();
        dynamic files = JsonConvert.DeserializeObject(json);
    }
}

反序列化本身起作用,但是我不知道如何遍历它们.

The deserialization itself working, but I don't know how to loop through them.

我也尝试这样做:

class ResFile
{
    public string name;
    public string hash;
    public int size;
}

并且以某种方式强制反序列化使用此功能,但是它当然行不通.

And somehow force the deserialization to use this, but it didn't work of course.

推荐答案

根据您的示例json,您的类为:

According to your sample json, your classes would be:

public class ResFile
{
    public string hash { set; get; }
    public int size { set; get; }
}

public class ResRoot
{
    public Dictionary<string, ResFile> Files { set; get; }
}


您可以反序列化为


You can deserialize as

var res = JsonConvert.DeserializeObject<ResRoot>(File.ReadAllText(filename));


foreach(var f in res.Files)
{
    Console.WriteLine("Name={0} Size={1}", f.Key, f.Value.size);
}

这篇关于从C#文件中反序列化Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆