c# 序列化
对接过的接口中使用到的序列化,由DataSet序列化 Json,由DataTable序列化 Json分别产生怎样的 Json格式,以及如何将格式转换为接口提供方需要的正确格式。
下面简单记录下:
1、DataSet 转换为 Json (ds中有两个Table):
string dsJson = JsonConvert.SerializeObject(ds); 得到的格式如下: { "Table": [{ "startProvinceName": "四川省", "startCityName": "成都市", "startAreaName": "", "endProvinceName": "湖北省", "endCityName": "武汉市", "endAreaName": "", "cargoName": "普货", "truckTypes": "厢车", "truckLength": 17.5, "lclCargo": "0", "weight": 25.9, "capacity": 70.9, "loadMethod": 1, "loadTimeDay": "2019-05-10", "loadTimeSegment": 0, "unLoadTimeDay": "2019-05-11", "unLoadTimeSegment": 0, "description": "发布货源测试", "internalOrderId": "CD201805-0015", "dispatcherTelphone": "18855667799", "assignDriverTelphone": "", "createContractFlag": "false" }], "Table1": [{ "preFreight": "", "arriveFreight": "", "receiptFreight": "", "daysForPayFreight": "", "contractLoadTime": "2019-05-10 18", "contractUnLoadTime": "2019-05-11 18", "note": "" }] }
2、DataTable 转化为 Json (上面DataSet中的两个Table)
[{ "startProvinceName": "浙江省", "startCityName": "宁波市", "startAreaName": "", "endProvinceName": "广东省", "endCityName": "深圳市", "endAreaName": "", "cargoName": "普货", "truckTypes": "厢车", "truckLength": 17.5, "lclCargo": "0", "weight": 1.0, "capacity": 1.0, "loadMethod": 1, "loadTimeDay": "2019-05-10", "loadTimeSegment": 0, "unLoadTimeDay": "2019-05-11", "unLoadTimeSegment": 0, "description": "发布货源测试", "internalOrderId": "NB201805-0025", "dispatcherTelphone": "18855667799", "assignDriverTelphone": "", "createContractFlag": "false" }]
[{ "preFreight": "", "arriveFreight": "", "receiptFreight": "", "daysForPayFreight": "", "contractLoadTime": "2019-05-10 18", "contractUnLoadTime": "2019-05-11 18", "note": "" }]
3、接口方需要的参数格式为:
{ "startProvinceName": "江苏省", "startCityName": "南京市", "startAreaName": "建邺区", "endProvinceName": "江苏省", "endCityName": "南京市", "endAreaName": "秦淮区", "cargoName": "龙虾", "truckTypes": "冷藏", "truckLength": "12.2", "lclCargo": 0, "weight": "13.3", "capacity": "14.4", "loadMethod": 1, "loadTimeDay": "2019-05-22", "loadTimeSegment": 4, "unLoadTimeDay": "2019-05-24", "unLoadTimeSegment": 4, "description": "小龙虾不要太好吃哇!", "internalOrderId": "111111111", "dispatcherTelphone": "17722221234", "assignDriverTelphone": "{{assignDriverTelphone}}", "createContractFlag": true, "createContractParam": { "preFreight": 1111, "arriveFreight": 3333, "receiptFreight": 7777, "daysForPayFreight": 0, "contractLoadTime": "2019-05-22 12", "contractUnLoadTime": "2019-05-24 12", "note": "靠谱老司机哇哇哇" } }
因此需要将DataSet 转换得到的格式 再进行下一步的转换,使用下面的方法:
先将DataSet中的第二个Table名称改为:createContractParam
ds.Tables[1].TableName = "createContractParam"; //下面进行转换: json = JsonConvert.SerializeObject(ds).Replace("\"Table\":[{", "").Replace("}],", ",").Replace("[", "").Replace("]", ""); ///以上就得到了对方提供的接口参数的格式