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 - , ",\"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);

输出:

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

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

  1. python 全栈开发,Day94(Promise,箭头函数,Django REST framework,生成json数据三种方式,serializers,Postman使用,外部python脚本调用django)

    昨日内容回顾 1. 内容回顾 1. VueX VueX分三部分 1. state 2. mutations 3. actions 存放数据 修改数据的唯一方式 异步操作 修改state中数据的步骤: ...

  2. 生成JSON数据--fastjson(阿里)方法

    fastjson(阿里)方法生成JSON数据: 与Gson类似,创建相应类,再使用JSON.toJSONString()添加对象 要求:生成如下JSON数据 1.{"age":3, ...

  3. 生成JSON数据--Gson(谷歌)方法

    Gson生成JSON数据方法: 创建相应的类,然后创建对象,toJson()进去就可以了 要求:生成如下JSON数据 1.{"age":4,"name":&qu ...

  4. 使用Ajax方式POST JSON数据包(转)

    add by zhj: 用ajax发送json数据时注意两点, 第一,使用JSON.stringify()函数将data转为json格式的字符串,如下 data: JSON.stringify({   ...

  5. 无限级分类及生成json数据

    第一步,先去数据库查询类别数据,然后交给生成json数据的函数处理,代码如下: /*生成类别JSON数据*/ public function wirteJson(){ $dataInfo = \thi ...

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

    0.前言     本文解释怎样使用Jquery中的ajax方法传递JSON数据包,传递的方法使用POST(当然PUT又有时也是一个不错的选择).POST JSON数据包相比标准的POST格式可读性更好 ...

  7. servlet生成json数据返回至Ajax

    一.JSON JSON是一种取代XML的数据结构,和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度. JSON就是一串字符串 只不过元素会使用特定的符号标 ...

  8. ASP生成JSON数据

    原文地址为:ASP生成JSON数据 < %@LANGUAGE = " VBSCRIPT "  CODEPAGE = " 65001 " % >    ...

  9. C#生成JSON数据

    protected void Page_Load(object sender, EventArgs e) { Response.Clear(); Response.ContentType = &quo ...

随机推荐

  1. MySQL使用位运算

    通常 我们的数据表中 可能会包含各种状态属性, 例如 blog表中,我们需要有字段表示其是否公开,是否有设置密码,是否被管理员封锁,是否被置顶等等. 也会遇到在后期运维中,策划要求增加新的功能而造成你 ...

  2. bzoj1382: [Baltic2001]Mars Maps

    Description 给出N个矩形,N<=10000.其坐标不超过10^9.求其面积并 Input 先给出一个数字N,代表有N个矩形. 接下来N行,每行四个数,代表矩形的坐标. Output ...

  3. Python的更多内容

    到目前为止,我们已经学习了绝大多数常用的Python知识.在这一章中,我们将要学习另外一些方面的Python知识,从而使我们对Python的了解更加 完整 . 1.特殊的方法 在类中有一些特殊的方法具 ...

  4. 如何重装air

    参考这里 很多年没有装过系统了,手贱用xxcleaner清理了下,好吧,我觉得只能重装了,直接贴过程吧 ,开机同时command+R,进入菜单 ,抹掉磁盘 ,重启,等在线更新(看各位运气了,网速好的话 ...

  5. svn merge 回滚

    聊一聊 svn merge 命令. svn 是啥就不用介绍了吧,谁用谁知道.有了 svn,开发者只要把代码提交上去,无论山崩地裂.电脑进水.硬盘格式化,哪怕换了一台电脑,都能随时把代码找回来.不过从自 ...

  6. Android sqlite管理数据库基本用法

    Android操作系统中内置了sqlite数据库(有关sqlite数据库详细介绍见:http://zh.wikipedia.org/wiki/SQLite),而sqllite本身是一个很小型的数据库, ...

  7. (VS TFS) Adding existing project to solution in TFS.

    正常的情况话,直接加入project,然后选择"Source control" -> “Add selected projects to source control.... ...

  8. unsigned char 转字符串:

    通常送显示的都是字符串,对于int long float转字符串有对应的函数,还有sprintf进行格式输出,对于嵌入式和单片机大多都用unsigned char型变量,转字符串需要自己编写函数,需要 ...

  9. JAVA 想让类无法new,可以使用private将类的构造函数改为私有的,这样new的时候就会报错了

    JAVA 想让类无法new,可以使用private将构造函数改为私有的,这样new的时候就会报错了 主要用于,静态工具类,静态类不需要new,直接使用   类名.静态方法  即可调用 class D{ ...

  10. log4j+logback+slf4j+commons-logging的关系与调试

    背景     由于现在开源框架日益丰富,好多开源框架使用的日志组件不尽相同.存在着在一个项目中,不同的版本,不同的框架共存.导致日志输出异常混乱.虽然也不至于对系统造成致命伤害,但是明显可以看出,架构 ...