c#中把json数据转到dataset中的方法

step1 构造类,建议用相关json工具生成类,这样效率高又准确呀

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
/// 
/// Trade 的摘要说明
/// 
/// 
namespace TRADE
{
    //方表對像
    public class List
    {
        public string Order_id;
        public string Order_sn;
        public string Deal_code;
        public string Order_status;
        public string Shipping_status;
        public string Pay_status;
        public string Process_status;
        public string Is_send;
        public string Is_locked;
        public string Is_separate;
        public string Shipping_id;
        public string Shipping_name;
        public string Pay_name;
        public string Pay_time;
        public string To_buyer;
        public string Postscript;
        public string Order_amount;
        public string Money_paid;
        public string User_id;
        public string User_nick;
        public string Consignee;
        public string Address;
        public string Zipcode;
        public string Tel;
        public string Mobile;
        public string Shipping_fee;
        public string Cz_shipping_fee;
        public string Province;
        public string City;
        public string District;
        public string Invoice_no;
        public string Add_time;
        public string Delivery_time;
        public string Sd_id;
        public string Ck_id;
        public string Create_time;
        public string Lylx;
        public string Shipping_time;
        public string Inv_payee;
        public string Inv_content;
        public string Order_note;
        public string Extension_id;
        public string Email;
        public string Goods_count;
        public string Is_emergency;
        public string Inv_status;
        public string Ckdm;
        public string Sddm;
        public string Sdmc;
        public string Sd_outer_code;
        public string CK_outer_code;
        public string Province_id;
        public string City_id;
        public string District_id;
    }
    public class Resp_data
    {
        public string Total_results;
        public string Page_no;
        public string Page_size;
        public List List;
    }
    public class Mast_Root
    {
        public Resp_data Resp_data;
    }
}

    



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace TRADE_DETAIL
{
    public class Orders
    {
        public string Goods_sn;
        public string Color_id;
        public string Size_id;
        public string Market_price;
        public string Sn;
        public string Color_code;
        public string Color_name;
        public string Size_code;
        public string Size_name;
        public string goods_number;
        public string payment_ft;

    }
    public class Resp_data
    {
        public string Order_id;
        public string Shipping_fee;
        public string Cz_shipping_fee;
        public string Province;
        public string City;
        public string District;
        public string User_id;
        public string Order_sn;
        public string Deal_code;
        public string Order_status;
        public string Shipping_status;
        public string Pay_status;
        public string Pay_time;
        public string To_buyer;
        public string Postscript;
        public string Order_amount;
        public string User_nick;
        public string Consignee;
        public string Address;
        public string Money_paid;
        public string Inv_payee;
        public string Inv_content;
        public string Order_note;
        public string Extension_id;
        public string Email;
        public string merge_new_order_sn;
        public string splite_new_order_sn;
        public string Sd_id;
        public string Ck_id;
        public string User_name;
        public string Ckdm;
        public string Sddm;
        public string Sd_outer_code;
        public string Ck_outer_code;
        public List Orders;
    }
    public class Detail_Root
    {
        public Resp_data Resp_data;
    }
}


step2 把json数据根据类结构解析成dataset数据

using System;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.IO.Compression;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using System.Web.UI;
using System.Data;
using userbill;
using System.Data.Common;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Serialization;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net.Sockets;
using System.Text;
using System.Drawing;
using MySql.Data.MySqlClient;
using System.Threading;//使用线程  
using System.Net;
using Newtonsoft.Json;//要从json官网下载此组件,附加到项目中就可以啦。
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;;//要从json官网下载此组件,附加到项目中就可以啦。
using System.Web.Script.Serialization;//.net 3.5版本以上才可以哟
//这里尽可能的多use一些 
//下面函数可以发http请求取得json数据,通用函数http请都都可以使用
private static String PostRequest(string url)
    {
        System.Net.HttpWebRequest hwRequest;
        System.Net.HttpWebResponse hwResponse;
        string strResult = string.Empty;
        byte[] bData;
        try
        {
            hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            // hwRequest.Timeout = 5000;
            hwRequest.Method = "POST";
            hwRequest.ContentType = "application/json;charset=UTF-8";
            bData = System.Text.Encoding.UTF8.GetBytes("");
            System.IO.Stream smWrite = hwRequest.GetRequestStream();
            smWrite.Write(bData, 0, bData.Length);
            smWrite.Close();
        }
        catch (System.Exception err)
        {
            WriteErrLog(err.ToString());
            return strResult;
        }

        //get response
        try
        {
            hwResponse = (HttpWebResponse)hwRequest.GetResponse();
            StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.UTF8);
            strResult = srReader.ReadToEnd();
            srReader.Close();
            hwResponse.Close();
        }
        catch (System.Exception err)
        {
            WriteErrLog(err.ToString());
        }

        return strResult;
    }


   public bool UPDATE_EFAST_TRADE(string sUser_id, string sPassword, string sStart_time, string sEnd_time, out string errMsg)//訂單數據同步
    {
        errMsg="";
        int RowCount = 0;
        SqlConnection POSCONN = new SqlConnection(POS_conn);
        try
        {
            POSCONN.Open();
            string sqlUser = "Select * from  table "
              + " WHERE U_ID='" + sUser_id + "'"
              + " AND U_MM='" + sPassword + "'";
            DataSet dsUser = new DataSet();
            SqlDataAdapter DAUser = new SqlDataAdapter(sqlUser, POS_conn);
            DAUser.SelectCommand.CommandTimeout = 0;
            DAUser.Fill(dsUser, "P_USER");
          
            if (dsUser == null || dsUser.Tables[0].Rows.Count == 0)
            {
                errMsg = "验证账号和密码不正确";
                return false;
            }
            else
            {
                for (int page=1; page < 10000; page++)//最大10000頁
                {
                    string sReauest = efast_url + "app_act=xxxxxx.get" + "&app_nick=" + app_nick + "&app_key=" + app_key + "&app_secret=" + app_secret + "&shipping_status=1"
                        + "&start_time=" + sStart_time + "&end_time=" + sEnd_time +"&page_no="+page.ToString ();
                  
                    string sJSON = PostRequest(sReauest);
                    TRADE.Mast_Root td = new TRADE.Mast_Root();//json解析关键部分

                    DateTime target = DateTime.Now;
             
                   
                    if (!String.IsNullOrEmpty(sJSON))
                    {
                        JavaScriptSerializer ser = new JavaScriptSerializer();//json解析关键部分
                        td = ser.Deserialize(sJSON);//json解析关键部分,在这里变成了list列表了,有list了把数据取出来就不是问题啦,循环就好啦。
                        if (Convert.ToInt64(td.Resp_data.Total_results) > 0 && td.Resp_data.List.Count>0)//有返回結果就續續
                        {
                            for (int i = 0; i < td.Resp_data.List.Count; i++)
                            {
                                string Order_ID = td.Resp_data.List[i].Order_sn.ToString();
                                if (Order_ID  != "")
                                {
                                    string sql_find = "Select * From EFAST_TRADE WHERE Order_SN='" + Order_ID + "'";
                                    if (!Efast.serverbase.dataIsExit(sql_find))//找不到才重新導
                                    {
                                        string sReauest_Detail = efast_url + "app_act=xxxxxx.get" + "&oid=" + Order_ID
                                           + "&feilds=shipping_fee,cz_shipping_fee,province,city,district,user_id,yfje,order_sn,deal_code,order_status,shipping_status,pay_status,pay_time,to_buyer,"
                                           + "postscript,order_amount,user_nick,consignee,address,orders.goods_sn,order_amount,money_paid,user_id,inv_payee,inv_content,order_note,extension_id,email,"
                                           + " sd_id,ck_id,orders.color_id,orders.size_id,orders.market_price,orders.goods_number,orders.payment_ft&type=1" + "&app_nick=" + app_nick + "&app_key=" + app_key + "&app_secret=" + app_secret;
                                        /*
                                         * http://121.43.104.171/efast_test/efast_api/webservice/web/index.php?app_act=efast.trade.detail.get&oid=512070000014&
                                         * feilds=shipping_fee,cz_shipping_fee,province,city,district,user_id,yfje,order_sn,deal_code,order_status,shipping_status,
                                         * pay_status,pay_time,to_buyer,postscript,order_amount,user_nick,consignee,address,orders.goods_sn,order_amount,money_paid,
                                         * user_id,inv_payee,inv_content,order_note,extension_id,email,sd_id,ck_id,orders.color_id,orders.size_id,orders.market_price&type=1
                                         * &app_nick=openapi&app_key=8888&app_secret=8888
                                         */
                                        string sJSON_DETAIL = PostRequest(sReauest_Detail);
                                        TRADE_DETAIL.Detail_Root detail = new TRADE_DETAIL.Detail_Root();
                                        if (!String.IsNullOrEmpty(sJSON_DETAIL))
                                        {
                                            JavaScriptSerializer serDetail = new JavaScriptSerializer();
                                            detail = serDetail.Deserialize(sJSON_DETAIL);
                                            if (detail.Resp_data.Orders.Count > 0)//有明細就轉
                                            {
                                                DataSet dsTRADE = new DataSet();
                                                dsTRADE = Query_TRADE();
                                                DataRow nrTrade = dsTRADE.Tables["EFAST_TRADE"].NewRow();
                                                nrTrade["order_id"] = td.Resp_data.List[i].Order_id.ToString();
                                                nrTrade["order_sn"] = td.Resp_data.List[i].Order_sn.ToString();
                                                nrTrade["Deal_code"] = td.Resp_data.List[i].Deal_code.ToString();
                                                nrTrade["Order_status"] = td.Resp_data.List[i].Order_status.ToString();
                                                nrTrade["Shipping_status"] = td.Resp_data.List[i].Shipping_status.ToString();
                                                nrTrade["Pay_status"] = td.Resp_data.List[i].Pay_status.ToString();
                                                nrTrade["Shipping_name"] = td.Resp_data.List[i].Shipping_name.ToString();
                                                nrTrade["Pay_name"] = td.Resp_data.List[i].Pay_name.ToString();
                                                nrTrade["Pay_time"] = Efast.serverbase.UnixTimestampToDateTime (target ,Convert.ToInt64(  td.Resp_data.List[i].Pay_time.ToString()));
                                                nrTrade["Order_amount"] = td.Resp_data.List[i].Order_amount.ToString();
                                                nrTrade["Money_paid"] = td.Resp_data.List[i].Money_paid.ToString();
                                                nrTrade["User_nick"] = td.Resp_data.List[i].User_nick.ToString();
                                                nrTrade["Consignee"] = td.Resp_data.List[i].Consignee.ToString();
                                                nrTrade["Address"] = td.Resp_data.List[i].Address.ToString();
                                                nrTrade["Zipcode"] = td.Resp_data.List[i].Zipcode.ToString();
                                                nrTrade["Tel"] = td.Resp_data.List[i].Tel.ToString();
                                                nrTrade["Mobile"] = td.Resp_data.List[i].Mobile.ToString();
                                                nrTrade["Shipping_fee"] = td.Resp_data.List[i].Shipping_fee.ToString();
                                                nrTrade["Cz_shipping_fee"] = td.Resp_data.List[i].Cz_shipping_fee.ToString();
                                                nrTrade["Province"] = td.Resp_data.List[i].Province.ToString();
                                                nrTrade["City"] = td.Resp_data.List[i].City.ToString();
                                               // nrTrade["District"] = td.Resp_data.List[i].District.ToString();
                                                nrTrade["Invoice_no"] = td.Resp_data.List[i].Invoice_no.ToString();
                                               // nrTrade["Add_time"] = td.Resp_data.List[i].Add_time.ToString();
                                                nrTrade["Add_time"] = Efast.serverbase.UnixTimestampToDateTime(target, Convert.ToInt64(td.Resp_data.List[i].Add_time.ToString()));
                                               // nrTrade["Delivery_time"] = td.Resp_data.List[i].Delivery_time.ToString();
                                                nrTrade["Delivery_time"] = Efast.serverbase.UnixTimestampToDateTime(target, Convert.ToInt64(td.Resp_data.List[i].Delivery_time.ToString()) );
                                               nrTrade["Delivery_time1"]=td.Resp_data.List[i].Delivery_time.ToString();
                                                nrTrade["Sd_id"] = td.Resp_data.List[i].Sd_id.ToString();
                                                nrTrade["Ck_id"] = td.Resp_data.List[i].Ck_id.ToString();
                                                nrTrade["Create_time"] = td.Resp_data.List[i].Create_time.ToString();
                                                nrTrade["Lylx"] = td.Resp_data.List[i].Lylx.ToString();
                                               // nrTrade["Shipping_time"] = td.Resp_data.List[i].Shipping_time.ToString();
                                                nrTrade["Shipping_time"] =Efast.serverbase.UnixTimestampToDateTime(target, Convert.ToInt64(td.Resp_data.List[i].Shipping_time.ToString()));
                                                nrTrade["Order_note"] = td.Resp_data.List[i].Order_note.ToString();
                                                nrTrade["Email"] = td.Resp_data.List[i].Email.ToString();
                                                nrTrade["Goods_count"] = td.Resp_data.List[i].Goods_count.ToString();
                                                nrTrade["Ckdm"] = td.Resp_data.List[i].Ckdm.ToString();
                                                nrTrade["Sddm"] = td.Resp_data.List[i].Sddm.ToString();
                                                nrTrade["Sddm"] = td.Resp_data.List[i].Sddm.ToString();
                                                nrTrade["Sdmc"] = td.Resp_data.List[i].Sdmc.ToString();
                                                nrTrade["Sd_outer_code"] = td.Resp_data.List[i].Sd_outer_code.ToString();
                                                nrTrade["CK_outer_code"] = td.Resp_data.List[i].CK_outer_code.ToString()!=null?td.Resp_data.List[i].CK_outer_code.ToString():"1201";
                                                dsTRADE.Tables["EFAST_TRADE"].Rows.Add(nrTrade);
                                                for (int j = 0; j < detail.Resp_data.Orders.Count; j++)
                                                {
                                                  DataRow nrDetail = dsTRADE.Tables["EFAST_TRADE_DETAIL"].NewRow();
                                                  nrDetail["order_id"] = detail.Resp_data.Order_id.ToString();
                                                  nrDetail["order_sn"] = detail.Resp_data.Order_sn.ToString();
                                                  nrDetail["Deal_code"] = detail.Resp_data.Deal_code.ToString ();
                                                  nrDetail["Shipping_fee"] = detail.Resp_data.Shipping_fee.ToString ();
                                                  nrDetail["Cz_shipping_fee"] = detail.Resp_data.Cz_shipping_fee.ToString ();
                                                  nrDetail["Province"] = detail.Resp_data.Province.ToString ();
                                                  nrDetail["City"] = detail.Resp_data.City.ToString ();
                                                  nrDetail["District"] = detail.Resp_data.District.ToString ();
                                                  nrDetail["Order_status"] = detail.Resp_data.Order_status.ToString ();
                                                  nrDetail["Shipping_status"] = detail.Resp_data.Shipping_status.ToString ();
                                                  nrDetail["Pay_status"] = detail.Resp_data.Pay_status.ToString ();
                                                 // nrDetail["Pay_time"] = Convert.ToDateTime (detail.Resp_data.Pay_time.ToString ());
                                                  nrDetail["Order_amount"] = detail.Resp_data.Order_amount.ToString ();
                                                  nrDetail["User_nick"] = detail.Resp_data.User_nick.ToString ();
                                                  nrDetail["Consignee"] = detail.Resp_data.Consignee.ToString ();
                                                  nrDetail["Address"] = detail.Resp_data.Address.ToString ();
                                                  nrDetail["Money_paid"] = detail.Resp_data.Money_paid.ToString ();
                                                  nrDetail["Order_note"] = detail.Resp_data.Order_note.ToString ();
                                                  nrDetail["is_HHF"] = detail.Resp_data.Order_note.ToString() .IndexOf ("换货追单")>=  0? 1  : 0;
                                                  nrDetail["Email"] = detail.Resp_data.Email.ToString ();
                                                  nrDetail["merge_new_order_sn"] = detail.Resp_data.merge_new_order_sn!=null?detail.Resp_data.merge_new_order_sn.ToString():"";
                                                  nrDetail["splite_new_order_sn"] = detail.Resp_data.splite_new_order_sn!=null?detail.Resp_data.splite_new_order_sn.ToString():"";
                                                  nrDetail["Sd_id"] = detail.Resp_data.Sd_id.ToString ();
                                                  nrDetail["Ck_id"] = detail.Resp_data.Ck_id.ToString ();
                                                  nrDetail["User_name"] = detail.Resp_data.User_name.ToString ();
                                                  nrDetail["Ckdm"] = detail.Resp_data.Ckdm.ToString ();
                                                  nrDetail["Sddm"] = detail.Resp_data.Sddm.ToString ();
                                                  nrDetail["Sd_outer_code"] = detail.Resp_data.Sd_outer_code.ToString ();
                                                  nrDetail["ck_outer_code"] = detail.Resp_data.Ck_outer_code.ToString() != null ? detail.Resp_data.Ck_outer_code.ToString() : "1201";
                                                  nrDetail["Goods_sn"] = detail.Resp_data.Orders[j].Goods_sn.ToString ();
                                                  nrDetail["Market_price"] = detail.Resp_data.Orders[j].Market_price.ToString ();
                                                  nrDetail["Sn"] = detail.Resp_data.Orders[j].Sn.ToString ();
                                                  nrDetail["Color_code"] = detail.Resp_data.Orders[j].Color_code.ToString ();
                                                  nrDetail["Color_name"] = detail.Resp_data.Orders[j].Color_name.ToString ();
                                                  nrDetail["Size_name"] = detail.Resp_data.Orders[j].Size_name.ToString();
                                                  nrDetail["goods_number"] = detail.Resp_data.Orders[j].goods_number.ToString();
                                                  nrDetail["payment_ft"] = detail.Resp_data.Orders[j].payment_ft.ToString();
                                                  dsTRADE.Tables["EFAST_TRADE_DETAIL"].Rows.Add(nrDetail);
                                                }
                                                   string[] sql = new string[2];
                                                   string[] tableName ={ "EFAST_TRADE", "EFAST_TRADE_DETAIL" };
                                                   sql[0] = " SELECT * FROM EFAST_TRADE  WHERE 1<>1  ";
                                                   sql[1] = " SELECT * FROM EFAST_TRADE_DETAIL WHERE 1<>1  ";
                                                   
                                                   if (!Efast.serverbase.Cliend_Data_Save(dsTRADE, sql, tableName, out errMsg))
                                                   {
                                                       return false;
                                                   }
                                                   RowCount++;
                                            }

                                        }

                                    }
                                }
                            }

                        }
                        else
                        {
                            break;//沒有結果就中斷
                        }
                    }

                   
                }
            }
            errMsg = RowCount.ToString ();
            return true;
        }
        catch (Exception e)
        {
            errMsg  = e.Message;
            return false;

        }
        finally
        {
            POSCONN.Close();
        }
 


你可能感兴趣的:(C#编程技术)