Deserializing JSON objects as List<type> not working with asmx service

扶醉桌前 提交于 2019-11-27 20:36:38
Chris Westbrook

I figured it out. I wasn't wrapping my JSON in an object like ASP.NET Ajax requires. For future viewers of this question, all JSON objects must be wrapped with a main object before being sent to the web service. The easiest way to do this is to create the object in JavaScript and use something like json2.js to stringify it. Also, if using an asmx web service, the objects must have a __type attribute to be serialized properly. An example of this might be:

var person=new object;
person.firstName="chris";
person.lastName="Westbrook";
person.seq=-1;
var data=new object;
data.p=person;
JSON.stringify(data);

This will create an object called p that will wrap a person object. This can then be linked to a parameter p in the web service. Lists of type person are made similarly, accept using an array of persons instead of just a single object. I hope this helps someone.

Could you show the JSON string you are trying to deserialize and the way you are using the Deserialize method? The following works fine:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace Test
{
    class Program
    {
        class Person 
        {
            public int SequenceNumber { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        public static void Main() 
        {
            string json = "[{\"SequenceNumber\":1,\"FirstName\":\"FN1\",\"LastName\":\"LN1\"},{\"SequenceNumber\":2,\"FirstName\":\"FN2\",\"LastName\":\"LN2\"}]";
            IList<Person> persons = new JavaScriptSerializer()
                .Deserialize<IList<Person>>(json);
            Console.WriteLine(persons.Count);
        }
    }
}

Or even simpler, when you are doing the $.ajax(...) use

data:"{\"key\":"+JSON.stringify(json_array)+"}",

and then on the other side of the code, make your function use the parameter "object key"

[WebMethod]
public static return_type myfunction(object key){...}
Mario Hernandez

SERVER SIDE

[WebMethod]
public void updatePeople(object json)

CLIENT SIDE

var person = "[{"seq":1,"firstName":"Chris","lastName":"Westbrook"}
,{"seq":2,"firstName":"sayyl","lastName":"westbrook"}]";

var str = "{'json':'" + JSON.stringify(person) + "'}";

I think the problem is what type you have to deserialize. You are trying to deserialize type

IList

but you should try to deserialize just

List

Since interface can not be instantiated this might is the root problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!