Deserialize Json from file in C#

做~自己de王妃 提交于 2020-01-24 02:52:05

问题


I've managed to find a solution without removing the paths from the keys.
Thanks for the help guys, and also pointing out problems, I really appreciate it! :)

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));
}




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

The Json file:

{
  "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.

I've also tried to do this:

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.


回答1:


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);
}



回答2:


Please follow the C# conventions and do not expose member variables as public or start property names with lower case. In order to make your conventional objects deserializable, you could use the System.Runtime.Serialization DataContract and DataMember attributes. DataContract indicates that an object of this type is serializable and DataMember is used to specify a property's serialization name.

class ResFile
{
    [DataMember(Name = "name")]
    public string Name { get; set; } 

    [DataMember(Name = "hash")]
    public string Hash { get; set; } 

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

    public ResFile () { }
}

[DataContract]
class ResFileCollection
{
    [DataMember(Name ="files")]
    public Dictionary<string, ResFile> Files { get; set; }
}

And here is the deserialization:

string json = File.ReadAllText("data.json");
        var files = JsonConvert.DeserializeObject<ResFileCollection>(json);
        foreach(KeyValuePair<string, ResFile> f in files.Files)
        {
            Console.WriteLine("{0} {1} {2}", f.Key, f.Value.Name, f.Value.Hash);
        }

Serialized property names should also be shorter for better performance. An example:

[DataMember(Name="src")]
public string SourcePath { get; set; }


来源:https://stackoverflow.com/questions/31774795/deserialize-json-from-file-in-c-sharp

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