Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize Json from file in C#

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.

like image 903
David Dosa Avatar asked Aug 02 '15 17:08

David Dosa


People also ask

How do I deserialize a JSON file?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JSON deserialize?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

What is JSON parse in C#?

Introduction to JSON Parser in C# JSON (JavaScript Object Notation) parse is language-independent which is a lightweight data-interchanging format, self-describing, and easy to understand. JSON parser is an alternative to XML it represents objects in structural text format and the data stored in key-value pairs.


2 Answers

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);
}
like image 171
EZI Avatar answered Oct 20 '22 17:10

EZI


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; }
like image 41
Alexander Ivanov Avatar answered Oct 20 '22 16:10

Alexander Ivanov