如何让我的aspx web方法将列表作为JSON对象返回?

时间:2012-12-29 07:28:37

标签: c# asp.net json web-services

我有一个返回对象的web方法。我需要将此对象转换为JSON对象,以便我可以通过我的Android应用程序使用它。 因此,我的问题是,为了将以下内容作为JSON对象返回,我需要做出哪些更改?

aspx代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace WebService4
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public List<Vehicle> GetCustomerList()
        {
            Vehicle vehi = simpleCase();
            List<Vehicle> newL = new List<Vehicle> { vehi };
            return newL;

        }

        [WebMethod]
        public Vehicle simpleCase()
        {
            Vehicle obj = new Vehicle();
            obj.VehicleID = "KL-9876";
            obj.VehicleType = "Nissan";
            obj.VehicleOwner = "Sanjiva";
            return obj;
        }
    }

    //someObject.SomeMethod(obj);

    public class Vehicle
    {
        public string VehicleID { get; set; }
        public string VehicleType { get; set; }
        public string VehicleOwner { get; set; }
    }




}

谢谢,任何帮助都将受到高度赞赏!

1 个答案:

答案 0 :(得分:1)

您可以使用http://james.newtonking.com/projects/json-net.aspx,序列化列表,然后返回一个字符串。

您也可以使用C#class JavaScriptSerializer

修改:这应该回答您的问题How can I return json from my WCF rest service (.NET 4), using Json.Net, without it being a string, wrapped in quotes?