如何使用对象名称反序列化json

时间:2010-11-19 13:57:48

标签: asp.net-mvc json json.net

我不确定如何说出这个问题但是,我有以下json:

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

使用json.net/javascriptserializer(asp.net)进行反序列化我有以下测试代码:

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);  
}

测试方法失败,因为两者都为null。我的代码反序列化有什么问题吗?

3 个答案:

答案 0 :(得分:1)

你需要一个中间课:

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; }
}

然后:

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);

答案 1 :(得分:0)

检查调试器中的对象,但我怀疑您需要测试doe.person.first_namedoe1.person.first_name

答案 2 :(得分:0)

这样做:

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

[编辑] 哦等等......也许你无法控制你收到的JSON,也无法改变它。如果是这样的话,那么Darin的解决方案将是您所需要的。