Search code examples
c#jsonjavascriptserializer

Deserializing json array


I'd like to deserialize a json string, but somehow i dont get the correct value :( This is the input json string

{
  "files":[
    {"path":"/c/asd/input.txt","size":13},
    {"path":"/c/asd/input.txt","size":136},
    {"path":"/c/asd/input.txt","size":483},
    {"path":"/c/asd/input.txt","size":136}
  ],
  "md5sum":"bbd88df7b2d8c95f922ebf0d718b5687"
}

Created a class for it

public class Files
    {
    public string path { get; set; }
    public int size { get; set; }
    }
public class myObject
    {
    public List<Files> files { get; set; }
    public string md5sum { get; set; }
    }

And trying to use JavaScriptSerializer:

var jss = new JavaScriptSerializer();
List<myObject> obj = s.Deserialize<List<myObject>>(File.ReadAllText(json));

What am i doing wrong? obj count is zero. I need to use only the path value.


Solution

  • That is one root object, not a list. Try:

    var obj = s.Deserialize<myObject>(File.ReadAllText(json));
    

    Also, I'm assuming that json here is a path to a file, and not the json itself.