szabieable
szabieable

Reputation: 123

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.

Upvotes: 1

Views: 133

Answers (3)

Shaiju Janardhanan
Shaiju Janardhanan

Reputation: 564

Your input json is not a list.Change Deserialize<List<myObject> to Deserialize<myObject>

Upvotes: 0

Davecz
Davecz

Reputation: 1221

Try

jss.Deserialize<myObject>(File.ReadAllText(json));

because you try deserialize a collection (List), but the s object is a not a collection.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064204

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.

Upvotes: 4

Related Questions