开发者

How to deserialize json with object name

开发者 https://www.devze.com 2023-01-26 03:01 出处:网络
I\'m not really sure how to phrase the problem but, I have the following json: { \"person\": { \"first_name\": \"John\",

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?


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消