c# 生成json数据包

json数据类型,归根到底就是一个字符串,管他里面什么格式,它就是一个字符串来的!

看一个json数据包:

{
    "touser":"OPENID",
    "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
    "url":"http://weixin.qq.com/download",
    "topcolor":"#FF0000",
    "data":
        {
            "User": {
            "value":"黄先生",
            "color":"#173177"
            },
            "Date":{
            "value":"06月07日 19时24分",
            "color":"#173177"
            },
            "CardNumber":{
            "value":"0426",
            "color":"#173177"
            },
            "Type":{
            "value":"消费",
            "color":"#173177"
            },
            "Money":{
            "value":"人民币260.00元",
            "color":"#173177"
            },
            "DeadTime":{
            "value":"06月07日19时24分",
            "color":"#173177"
            },
            "Left":{
            "value":"6504.09",
            "color":"#173177"
            }
        }
}

你可以直接赋值一个string对象:

string json = "{\"touser\":\"OPENID\",.......}";

遇到双引号要使用转义“\”进行转义。这样弄出来的一个string对象就是一个json数据包了。

这样直接赋值麻烦,在网上找了找,为了生成上面这样的json,弄到了下面几个类:

PayTemplateHeader.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace tenpay
{
    [DataContract]
    public class PayTemplateHeader
    {
        public PayTemplateHeader() { }

        public PayTemplateHeader(string template_id, string touser, string url)
        {
            this.template_id = template_id;
            this.touser = touser;
            this.url = url;
        }

        /// <summary>
        /// 模板ID
        /// </summary>
        [DataMember]
        public string template_id { get; set; }

        /// <summary>
        /// 微信接收信息用户的openid
        /// </summary>
        [DataMember]
        public string touser { get; set; }

        /// <summary>
        /// 信息点击链接
        /// </summary>
        [DataMember]
        public string url { get; set; }
    }
}

PayTemplate.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace tenpay
{
    /// <summary>
    /// 微信充值模板接口请求实体对象
    /// </summary>
    [DataContract]
    public class PayTemplate
    {
        public PayTemplate() { }

        /// <summary>
        /// 您好,您已成功进行某游戏币充值。
        /// </summary>
        [DataMember]
        public string first { get; set; }

        /// <summary>
        /// 帐号:kantzou
        /// </summary>
        [DataMember]
        public string accountType { get; set; }

        /// <summary>
        /// 帐号:kantzou
        /// </summary>
        [DataMember]
        public string account { get; set; }

        /// <summary>
        /// 获得游戏币:500点
        /// </summary>
        [DataMember]
        public string productType { get; set; }

        /// <summary>
        /// 获得游戏币:500点
        /// </summary>
        [DataMember]
        public string number { get; set; }

        /// <summary>
        /// 充值金额:50元
        /// </summary>
        [DataMember]
        public string amount { get; set; }

        /// <summary>
        /// 充值状态:充值成功
        /// </summary>
        [DataMember]
        public string result { get; set; }

        /// <summary>
        /// 祝您游戏愉快。
        /// </summary>
        [DataMember]
        public string remark { get; set; }
    }
}

JSONHelper.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace tenpay
{
    /// <summary>
    /// json转化类
    /// </summary>
    [Serializable]
    public class JSONHelper
    {
        public static string Serialize<T>(T obj)
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, obj);
            string retVal = Encoding.UTF8.GetString(ms.ToArray());
            ms.Dispose();
            return retVal;
        }

        public static T Deserialize<T>(string json)
        {
            T obj = Activator.CreateInstance<T>();
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            obj = (T)serializer.ReadObject(ms);
            ms.Close();
            ms.Dispose();
            return obj;
        }
    }
}
    public class DataFormat
    {
        public string value { get; set; }
        public string color { get; set; }
    }

    public class DataFormatList
    {
        public List<DataFormat> first { get; set; }
        public List<DataFormat> accountType { get; set; }
        public List<DataFormat> account { get; set; }
        public List<DataFormat> productType { get; set; }
        public List<DataFormat> number { get; set; }
        public List<DataFormat> amount { get; set; }
        public List<DataFormat> result { get; set; }
        public List<DataFormat> remark { get; set; }
    }  
        /// <summary>
        /// 微信充值模板接口json参数整理
        /// </summary>
        /// <param name="PayTemplate">微信充值模板接口参数实例</param>
        /// <returns></returns>
        public string getPayTemplateJson(PayTemplateHeader header, PayTemplate template,string color)
        {
            string jsonH = JSONHelper.Serialize<PayTemplateHeader>(header);

            DataFormatList dataformatlist = new DataFormatList();

            dataformatlist.first = new List<DataFormat>(){
            new DataFormat(){value=ConvertGBK(template.first),color=color}};

            dataformatlist.accountType = new List<DataFormat>(){
            new DataFormat(){value=ConvertGBK(template.accountType),color=color}};

            dataformatlist.account = new List<DataFormat>(){
            new DataFormat(){value=ConvertGBK(template.account),color=color}};

            dataformatlist.productType = new List<DataFormat>(){
            new DataFormat(){value=ConvertGBK(template.productType),color=color}};

            dataformatlist.number = new List<DataFormat>(){
            new DataFormat(){value=ConvertGBK(template.number),color=color}};

            dataformatlist.amount = new List<DataFormat>(){
            new DataFormat(){value=ConvertGBK(template.amount),color=color}};

            dataformatlist.result = new List<DataFormat>(){
            new DataFormat(){value=ConvertGBK(template.result),color=color}};

            dataformatlist.remark = new List<DataFormat>(){
            new DataFormat(){value=ConvertGBK(template.remark),color=color}};

            string jsonD = new JavaScriptSerializer().Serialize(dataformatlist);

            string json = jsonH.Insert(jsonH.Length - 1, ",\"data\":" + jsonD.Replace("[", "").Replace("]", ""));

            return json;
        }

        private string ConvertGBK(string p)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(p);
            return Encoding.GetEncoding("GBK").GetString(byteArray);
        }

调用例子:

        PayTemplateHeader header = new PayTemplateHeader();
        header.template_id = "jrciIIcHIYLJujC7FyqSiKyGGWnLok6VQJ1a81p1HLw";
        header.touser = "openid123";
        header.url = "http://www.baidu.com/App/Pay/1.aspx";

        PayTemplate paytemplate = new PayTemplate();
        paytemplate.first = "您好,您已成功进行某游戏币充值。";
        paytemplate.accountType = "账号";
        paytemplate.account = "k6780384";
        paytemplate.productType = "游戏币";
        paytemplate.number = "500点";
        paytemplate.amount = "50元";
        paytemplate.result = "充值成功";
        paytemplate.remark = "祝您游戏愉快";
        TenpayUtil tenpay = new TenpayUtil();
        string post_data = tenpay.getPayTemplateJson(header, paytemplate, "#173177");
        Response.Write(post_data);

输出:

哎,乱码了,不管了,只要微信那边不是乱码就好。

时间: 2024-08-07 10:55:41

c# 生成json数据包的相关文章

Java-封装生成JSON数据和XML数据类

1.背景 借鉴与php中 app接口的实现(php写app接口生成xml和json数据),封装了java版的json和xml数据操作类! 2.准备 在使用之前,需要引入 json 的jar 包:点我下载 ! 这里实现了,对象转json , 对象集合转json, 对象转xml,对象集合转xml ; 3.appUtil 工具类实现 具体的实现过程,我就不解释了,一边写,一边测试!直到写成为止! 里面的 tojsonArray() 方法 没有使用,可以删除,不过想生成json数组的 ,就不需要删除了!

CoAP学习笔记——nodeJS node-coap返回JSON数据包

0 前言 本文说明如何使用node-coap返回JSON数据包.CoAP是专门为物联网系统开发的面向网络的应用层协议栈,CoAP建立在UDP协议之上尽可能减少网络开销,又具有HTTP Restful类型的特性.node-coap使用nodejs实现了coap的客户端和服务器端. [测试环境]--ubuntu/Linux [相关博文] [CoAP协议文档--The Constrained Application Protocol (CoAP)] [CoAP协议学习--CoAP基础] [CoAP学习

在SQL 中生成JSON数据

这段时间接手一个数据操作记录的功能,刚拿到手上的时候打算用EF做,后来经过仔细考虑最后还是觉定放弃,最后思考再三决定: 1.以模块为单位分表.列固定(其实可以所有的操作记录都放到同一个表,但是考虑到数据量大的时候查询性能的问题还是分表吧)列:主键ID.引用记录主键ID.操作时间.操作类型.详细信息(里面存储的就是序列化后的值) 2.在客服端解析保存的序列化的值 但是用xml还是用json呢,这有是一个问题,显然用xml在存储过程正很容易就能生成了:SELECT * FROM TABLE FOR 

前端学习——使用Ajax方式POST JSON数据包

0.前言 本文解释如何使用Jquery中的ajax方法传递JSON数据包,传递的方法使用POST(当然PUT又有时也是一个不错的选择).POST JSON数据包相比标准的POST格式可读性更好些,层次结构也更清晰. 为了说明问题,前端和后端较为简单,重点突出AJAX的应用. [前端]--add-post-json.html 图1 add页面 [后端]--add-post-json.php <?php // 返回JSON格式 header('Content-Type:application/jso

ASP生成JSON数据

原文地址为:ASP生成JSON数据 < %@LANGUAGE = " VBSCRIPT "  CODEPAGE = " 65001 " % >  < ! -- #include file = " json.asp " -->  < ! -- #include file = " inc/Conn.asp "   -->  < %response.ContentType = " 

黑马day17 xstream生成xml数据&amp;json-lib生成json数据

1.XStream工具介绍: 这个工具即这个工具的jar包可以帮我们把JavaBean,集合(List,Set,Map)等生成xml格式的数据 jar包: xstream-1.4.4.jar 这是核心包 xpp3_min-1.1.4c.jar 这是必须依赖的包 只要导入这两个jar包 导入到构建路径中就可以使用了.. 2.json-lib介绍: 这个jar包可以帮我们把JavaBean,集合(List,Set,Map)等生成json格式的数据 jar包: 这是核心包 这是核心包的依赖包 为了方便

CEF生成JSON数据

在"使用CEF的JSON解析功能"中介绍了使用CefParseJson方法,与之对应的还有一个CefWriteJson方法,可以用来生成JSON串(或二进制),其函数原型如下: // Generates a JSON string from the specified root |node| which should be a // dictionary or list value. Returns an empty string on failure. This method //

MQ 分拆Json数据包然后上传

public void UploadInsurHistory() { using (IDbConnection connection = ConnConfig.DmsConnection) { IDbTransaction trans = connection.BeginTransaction(); try { InsuranceBuyAccess gateway = new InsuranceBuyAccess(trans); CommonDataGateway commonDataGatew

js生成json数据

<script src="~/static/js/jquery.min.js"></script><script type="text/javascript"> var list = [];//创建数组 var a1 = {};//创建对象 a1.t = "a"; a1.v = "b,s,g"; var a2 = {}; a2.t = "c"; a2.v = "