需要更改从JSON返回的数据格式

时间:2014-04-03 09:29:22

标签: asp.net json web-services

我正在创建一个webservice,它应该从数据库(sql server)获取数据并返回它。 每件事都很好。但我需要的是我需要以我需要的格式显示数据。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;


namespace Webservice
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [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
    {
        public Service1()
        {
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
       // public string GetEmployees(string SearchTerm)
        public string GetEmployees()
        {
            try
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
                con.Open();
                SqlCommand cmd = new SqlCommand();
                //cmd.CommandText = "SELECT *  FROM Contact e WHERE FirstName LIKE '%" + SearchTerm + "%'";
                cmd.CommandText = "SELECT *  FROM Contact e ";
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.SelectCommand.Connection = con;
                da.Fill(ds);
                con.Close();
                // Create a multidimensional array
                string[][] EmpArray = new string[ds.Tables[0].Rows.Count][];
                int i = 0;
               foreach (DataRow rs in ds.Tables[0].Rows)
                {
                        //EmpArray[i] = new string[] { rs["FirstName"].ToString(), rs["LastName"].ToString(), rs["Contactno"].ToString() };
                    EmpArray[i] =  new string[] { "FNAME: " + rs["FirstName"].ToString(), "LName: " + rs["LastName"].ToString(), "Contactno: " + rs["Contactno"].ToString()};
                    i = i + 1;
                }
                // Return JSON data
                JavaScriptSerializer js = new JavaScriptSerializer();

                string strJSON = js.Serialize(EmpArray);
                return strJSON;
            }
            catch (Exception ex) { return errmsg(ex); }
        }

        public string errmsg(Exception ex)
        {
            return "[['ERROR','" + ex.Message + "']]";
        }
     }
 }

这是我的输出:

[["FNAME: devi","LName: priya ","Contactno: 965577796 "],
["FNAME: arun","LName: kumar  ","Contactno: 9944142109"],
["FNAME: karu ","LName: ronald","Contactno: 8883205008"]]

但是我需要以下格式的结果:(应该包含花括号,并且在开始每个名称时使用货物这个词,值应该以双重代码开头和结尾..

{ "Cargo": [ {  "FNAME": "devi", "LName": "priya " }, 
{"FNAME": "arun", "LName": "kumar" }, {  "FNAME": "karu ", "LName": "ronald" }] }

1 个答案:

答案 0 :(得分:0)

以下代码解决了我的问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;




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

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

     [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
        //public string GetEmployees(string SearchTerm) 

        public void CargoNet()
        {
            try
            {
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT TOP 1 * FROM cargo_tracking ";
                DataSet ds = new DataSet();
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.SelectCommand.Connection = con;
                da.Fill(dt);
                con.Close();
                List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                Dictionary<string, object> row = null;
                foreach (DataRow rs in dt.Rows)
                {
                    row = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, rs[col].ToString().Trim());
                    }
                    rows.Add(row);
                }
               //return serializer.Serialize(rows);
                //return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
                //JavaScriptSerializer js = new JavaScriptSerializer();
                //string strJSON = js.Serialize(new { Cargo = rows });
                this.Context.Response.ContentType = "application/json; charset=utf-8";
                this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
                //return serializer.Serialize(new { Cargo = rows });

            }
            catch (Exception ex)
            {
                //return errmsg(ex);
            }
        }     
        public string errmsg(Exception ex)
        {
            return "[['ERROR','" + ex.Message + "']]";
        }
     }