inspectorGadget
inspectorGadget

Reputation: 127

deserialization of json file to poco object not working

I am trying to instantiate a poco object with data in a .json file in my VS project. When I use this code, it just returns an empty object.

Class:

public class Person
{
    public int id { get; set; }
    public string name { get; set; }
}

Json text in in file:

{
    "person": 
    {
        "id": 1,
        "name": "joe"
    }
}

Code in Program.cs:

static void Main(string[] args)
{
    string jspath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Json\json1.json");

    //person object results in 0 for id and null for name (empty)
    Person person = new JavaScriptSerializer().Deserialize<Person>(File.ReadAllText(jspath ));
}

What am I doing wrong?

Upvotes: 2

Views: 71

Answers (1)

Daniel
Daniel

Reputation: 9829

Your JSON file is not correct.

It should be:

{ "id": 1, "name": "joe" }

Proof:

Person p = new Person
{
    id = 1,
    name = "joe"
};
var sb = new StringBuilder();
new JavaScriptSerializer().Serialize(p, sb);
Console.WriteLine(sb.ToString()); // Outputs: { "id": 1, "name": "joe" }

Upvotes: 2

Related Questions