bonskijr
bonskijr

Reputation: 29

How to deserialize json with object name

I'm not really sure how to phrase the problem but, I have the following json:

{
  "person": {
    "first_name": "John",
    "gender": "M",
    "last_name": "Doe"
  }
}

And deserializing using json.net/javascriptserializer(asp.net) I have the following test code:

public class Person 
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string gender { get; set; }
}


[Test]
public void TestDeserialize() 
{
    string json = @"{""person"":{""first_name"":""John"",""gender"":""M"",""last_name"":""Doe""}}";

    var serializer = new JavaScriptSerializer(); // asp.net mvc (de)serializer

    Person doe = serializer.Deserialize<Person>(json);
    Person doe1 = JsonConvert.DeserializeObject<Person>(json); // json.net deserializer

    Assert.AreEqual("John", doe.first_name);
    Assert.AreEqual("John", doe1.first_name);  
}

The test method fails, because both are null. Anything wrong with my code to deserialize?

Upvotes: 0

Views: 1584

Answers (3)

Hector Correa
Hector Correa

Reputation: 26690

This will do it:

        string json = @"{'first_name':'John','gender':'M','last_name':'Doe'}";           
        var serializer = new JavaScriptSerializer(); 
        Person doe = serializer.Deserialize<Person>(json);

[EDIT] Oh wait...perhaps you are not in control of the JSON that you receive and cannot change it. If that's the case then Darin's solution would be what you need.

Upvotes: 0

Basic
Basic

Reputation: 26766

Examine the object in the debugger but I suspect you need to test doe.person.first_name and doe1.person.first_name

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You need an intermediary class here:

public class Model
{
    public PersonDetails Person { get; set; }
}

public class PersonDetails
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string gender { get; set; }
}

and then:

string json = @"{""person"":{""first_name"":""John"",""gender"":""M"",""last_name"":""Doe""}}";
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize<Model>(json);
Assert.AreEqual("John", model.Person.first_name);

Upvotes: 1

Related Questions