需要从JSON更改retun数据的格式 [英] Need to change the format of retun data from JSON
本文介绍了需要从JSON更改retun数据的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
我正在创建一个webservice,它应该从数据库(sql server)获取数据并将其返回。
每件事都很好。但是我需要的是我需要以我需要的格式显示数据。
这是我的代码:
使用System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;使用System.Web.Services
;
使用System.Web.Script.Serialization;
使用System.Web.Script.Services;
使用System.Data;
使用System.Data.SqlClient;
使用System.Configuration;使用System.ComponentModel
;
名称空间Webservice
{
///< summary>
/// Service1
///< / summary>的摘要说明
[WebService(Namespace =http://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
/ /要允许使用ASP.NET AJAX从脚本调用此Web Service,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class Service1:System.Web.Services.WebService
{
public Service1()
{
//如果使用设计的组件,则取消注释以下行
// 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();
//创建一个多维数组
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;
}
//返回JSON数据
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(EmpArray);
返回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}}}
可以任意一个请帮帮我
提前致谢。
解决方案
使用下面的帮助代码
private static 字典<字符串,字典<字符串,对象> > DatatableToDictionary(DataTable dt)
{
var cols = dt.Columns.Cast< DataColumn>();
return dt.Rows.Cast< DataRow>()
.ToDictionary(r = > dt.Rows.IndexOf(r).ToString(),
r = > cols.ToDictionary(c = > c.ColumnName,c = > r [c.ColumnName]));
}
public Dictionary< string,Dictionary< 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();
返回DatatableToDictionary(ds.Tables [0]);
}
catch(Exception ex){return errmsg(ex); }
}
你好b $ b
我的代码做了一些改动现在它完美无缺/>
这是我的代码:
< pre lang = xml> public string GetEmployees()
{
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 * FROM Contact e;
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]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
public string errmsg(Exception ex)
{
return [[' ERROR',' + ex.Message + ']];
}
她是我的结果:
{Cargo:[{Id:1,FirstName:devi,LastName:priya,Contactno:965577796} ,{Id:2,FirstName:arun,LastName:kumar,Contactno:9944142109},{Id:3,FirstName:karu,LastName : 罗纳德, Contactno: 8883205008}]}
Hi
I'm creating a webservice which should get data from database(sql server) and return it.
Every thing working fine.But what i need is i need to display the data with the format which i need.
Here is my code:
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 + "']]"; } } }
Here is my output:
[["FNAME: devi","LName: priya ","Contactno: 965577796 "], ["FNAME: arun","LName: kumar ","Contactno: 9944142109"], ["FNAME: karu ","LName: ronald","Contactno: 8883205008"]]
but i need the result in following format:(which should contain curly braces and the word cargo at starting.
{ "Cargo": [ { "FNAME": "devi", "LName": "priya " }, {"FNAME": "arun", "LName": "kumar" }, { "FNAME": "karu ", "LName": "ronald" }] }
can any one please help me
Thanks in advance.
解决方案
Use below helper code
private static Dictionary<string, Dictionary<string, object>> DatatableToDictionary(DataTable dt) { var cols = dt.Columns.Cast<DataColumn>(); return dt.Rows.Cast<DataRow>() .ToDictionary(r => dt.Rows.IndexOf(r).ToString(), r => cols.ToDictionary(c => c.ColumnName, c => r[c.ColumnName])); }
public Dictionary<string, Dictionary<string, object>> 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(); return DatatableToDictionary(ds.Tables[0]); } catch (Exception ex) { return errmsg(ex); } }
Hi
I made few changes in my code now it works perfect
Here is my code:
<pre lang="xml">public string GetEmployees() { 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 * FROM Contact e "; 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]); } rows.Add(row); } return serializer.Serialize(rows); } public string errmsg(Exception ex) { return "[['ERROR','" + ex.Message + "']]"; }
her is my result:
{ "Cargo": [{"Id":1,"FirstName":"devi","LastName":"priya","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},{"Id":3,"FirstName":"karu ","LastName":"ronald","Contactno":"8883205008"}]}
这篇关于需要从JSON更改retun数据的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文