最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to correctly deserialize a JSON string into the class that contains a nested List of another class - Stack Overflow

programmeradmin3浏览0评论

I have the following object graph and I'm using Jquery's $.Ajax() to send this identical "View" object in JSON (stringified) from the browser to a Page Method on ASP.Net. The JAvascript deserialization works for all of the strings and int's in the View class but My List<DataItem> is empty.

What I tried: Using chrome dev tools, I took the stringified JSON, created a unit test and used both the DataContractJsonSerializer and the JavaScriptSerializer. The DataContractJsonSerializer object deserialized my object graph correctly but the JavaScriptSerializer dumped my List. How can I get the correct deserialization on my page method ?

public class View
{
    public string Text { get; set; }
    public string AnotherText { get; set; }
    public Int SomeInt { get; set; }
    public List<DataItem> { get; set; }
}

public class DataItem
{
    public Person person {get;set}
}

public class Person
{
    public int Age {get;set}
}

   var dataa = {mqvm: mqvmJSON };
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify( dataa ),
        url: "GoHere.aspx/WebMethodName",
        success: function(data) {
            alert(data.d);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText + ' ' + errorThrown);
        }
    });

Instead of this (the view obj as a param).

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public static string CreateResponseReview(View mqvm)
    { 
        return "Success";
    }

how can I get this? (the string param)

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public static string CreateResponseReview(string mqvm)
    { 
        //do manual JSON deserialization here.

        return "Success";
    }

My JSON looks like this.

    {
    "Text": "6",
    "AnotherText":"wow"
    "SomeInt": 5,
    "DataItem":[
        {
            "person":{
                "Age":23
            }
        },
        {
            "person":{
                "Age":42
            }
        }
    ]
}

I have the following object graph and I'm using Jquery's $.Ajax() to send this identical "View" object in JSON (stringified) from the browser to a Page Method on ASP.Net. The JAvascript deserialization works for all of the strings and int's in the View class but My List<DataItem> is empty.

What I tried: Using chrome dev tools, I took the stringified JSON, created a unit test and used both the DataContractJsonSerializer and the JavaScriptSerializer. The DataContractJsonSerializer object deserialized my object graph correctly but the JavaScriptSerializer dumped my List. How can I get the correct deserialization on my page method ?

public class View
{
    public string Text { get; set; }
    public string AnotherText { get; set; }
    public Int SomeInt { get; set; }
    public List<DataItem> { get; set; }
}

public class DataItem
{
    public Person person {get;set}
}

public class Person
{
    public int Age {get;set}
}

   var dataa = {mqvm: mqvmJSON };
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify( dataa ),
        url: "GoHere.aspx/WebMethodName",
        success: function(data) {
            alert(data.d);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText + ' ' + errorThrown);
        }
    });

Instead of this (the view obj as a param).

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public static string CreateResponseReview(View mqvm)
    { 
        return "Success";
    }

how can I get this? (the string param)

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public static string CreateResponseReview(string mqvm)
    { 
        //do manual JSON deserialization here.

        return "Success";
    }

My JSON looks like this.

    {
    "Text": "6",
    "AnotherText":"wow"
    "SomeInt": 5,
    "DataItem":[
        {
            "person":{
                "Age":23
            }
        },
        {
            "person":{
                "Age":42
            }
        }
    ]
}
Share Improve this question edited Sep 27, 2011 at 13:13 EbbnFlow asked Sep 26, 2011 at 18:40 EbbnFlowEbbnFlow 6631 gold badge10 silver badges18 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 12

I figured it out.

I didn't want to use the JavascriptSerializer class because it dumped my nested list so I forced it to pass me the object as a string and then I manually deserialized it. I also kept getting "no parameterless constructor defined for type of u0027system.string u0027"

Remember that U0027 is an apostrophe so the runtime might be thinking that there is an actual type named "System.string" and not System.string. My problem was - I wasn't correctly delimiting the parameters in the item below called data2. I had to put \' ticks \' around the key and the value.

function requestHtmlFromServer(mqvmJSON) {
    var mqvmstring = JSON.stringify(mqvmJSON);
    var data2 = "{\'mqvm\':\'" + mqvmstring + "\' }"; \\<--the problem
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: data2,
        url: "MedicalInformation.aspx/CreateResponseReview",
        success: function(data) {
            alert(data.d);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText + ' ' + errorThrown);
        }
    });
}


    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public static string CreateResponseReview(string mqvm)
    {
        string noNewLines = mqvm.Replace("\n", "");
        View viewModel = ToObjectFromJSON<View>(noNewLines);
        //do my other stuff here

        return "Success";
    }
    public static T ToObjectFromJSON<T>(string jsonString)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
        var newObject = (T)serializer.ReadObject(memoryStream);
        memoryStream.Close();
        return newObject;
    }

Try using the following:

Deserialisation Code

string json = "{\"text\":\"some text\",\"anotherText\":\"some more text\", \"someInt\":1, \"dataItems\":[{\"person\":{age:25}},{\"person\":{age:20}}]}";

JavaScriptSerializer serializer = new JavaScriptSerializer();
View view = serializer.Deserialize<View>(json);

Classes

public class View
{
    public string Text { get; set; }
    public string AnotherText { get; set; }
    public int SomeInt { get; set; }
    public List<DataItem> DataItems { get; set; }
}

public class DataItem
{
    public Person person { get; set; }
}

public class Person
{
    public int Age {get;set;}
}

JSON

{
    "text":"some text",
    "anotherText":"some more text", 
    "someInt":1, 
    "dataItems":
        [
            {"person":{age:25}},
            {"person":{age:20}}
        ]
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论