XSLT存档  

不及格的程序员-八神

 查看分类:  ASP.NET XML/XSLT JavaScripT   我的MSN空间Blog
随笔 - 879,  文章 - 0,  评论 - 1190,  阅读 - 34万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Flint.Util;
using System.Globalization;
using System.Web.Script.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Runtime.Serialization;
 
namespace WebTest
{
    [DataContractAttribute]
    public class tt
    {
        [DataMember]
        public string content
        {
            set;
            get;
        }
    }
    public partial class _Default : System.Web.UI.Page
    {
        public static string JsonSerializer<T>(T t)
       {
           DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
          MemoryStream ms = new MemoryStream();
           ser.WriteObject(ms, t);
           string jsonString = Encoding.UTF8.GetString(ms.ToArray());
          ms.Close();
          return jsonString;
       }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            DateTimeFormatInfo myDTFI = new CultureInfo("zh-CN", false).DateTimeFormat;
 
            // Creates a DateTime with the Gregorian date January 3, 2002 (year=2002, month=1, day=3).
            // The Gregorian calendar is the default calendar for the en-US culture.
            DateTime myDT = DateTime.Now;
            Response.ContentType = "application/json";
 
            // Displays the format pattern associated with each format character.
            Console.WriteLine("FORMAT  en-US EXAMPLE");
 
            var jserial = new JavaScriptSerializer();
            this.Response.Write(Server.HtmlDecode(jserial.Serialize(new
            {
                content = "<p><a href=\"http://www.google.com\">google</a><img src=\"http://pic.cnblogs.com/face/u13330.jpg\" /></p>"/*.Replace("<", "<").Replace(">", ">")*/
            })));
 
            this.Response.Write(JsonSerializer(new tt() { content = "<p><a href=\"http://www.google.com\">google</a><img src=\"http://pic.cnblogs.com/face/u13330.jpg\" /></p>" }));
            this.Response.End();
             
            
            this.Response.Write(string.Format("{0}", myDT.ToString("dddd", myDTFI)));
 
        }
    }
}

 

"<p><a href=\"http://www.google.com\">google</a><img src=\"http://pic.cnblogs.com\" /></p>"

同样一段html代码使用两种序列化方式有不同的结果.

DataContractJsonSerializer 与 JavaScriptSerializer 结果分别为:

"<p><a href=\"http:\/\/www.google.com\">google<\/a><img src=\"http:\/\/pic.cnblogs.com\" \/><\/p>"

"\u003cp\u003e\u003ca href=\"http://www.google.com\"\u003egoogle\u003c/a\u003e\u003cimg src=\"http://pic.cnblogs.com\" /\u003e\u003c/p\u003e"

对于iPhone/Android客户端的显示的数据,明显前者比较好哦, 前且不用转义.

原来后者API已过时:)

The VS2008 complier reports a Warning of "'System.Web.Script.Serialization.JavaScriptSerializer.JavaScriptSerializer()' is obsolete: 'The recommended alternative is System.Runtime.Serialization.DataContractJsonSerializer.'" on the line of code "JavaScriptSerializer ser = new JavaScriptSerializer();" the warning reports the wrong namespace to find the new class. The actual namespace is "System.Runtime.Serialization.Json.DataContractJsonSerializer".


 

 solidus 是需要转义的 

{"error":null,"message":null,"ClientInfo":[{"AttachmentList":[{"name":"原附件","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55882"},{"name":"加1附件","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55890"}],"bz":"","cbsCode":"W0476","cbsName":"生产服务140701公司","dz":"地址","frdb":"公司","frdh":"","lxr":"联系人","lxrdh":"18302418581","shxydm":"SCFW140701","ty":0,"ywfw":"","zjsj":"2024-12-27 09:37:47"},{"AttachmentList":[{"name":"原附件","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55883"},{"name":"1","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55884"},{"name":"2","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55885"},{"name":"亿方登录","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55886"},{"name":"招投标算法","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55887"}],"bz":"","cbsCode":"W0477","cbsName":"生产服务1407","dz":"地址","frdb":"生产","frdh":"","lxr":"","lxrdh":"18302418581","shxydm":"SCFW1407","ty":0,"ywfw":"","zjsj":"2024-12-27 09:37:39"}]}sendJSONRequest
--------------------------------------------------------------------------------
{"error":null,"message":null,"ClientInfo":[{"AttachmentList":[{"name":"原附件","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55882"},{"name":"加1附件","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55890"}],"bz":"","cbsCode":"W0476","cbsName":"生产服务140701公司","dz":"地址","frdb":"公司","frdh":"","lxr":"联系人","lxrdh":"18302418581","shxydm":"SCFW140701","ty":0,"ywfw":"","zjsj":"2024-12-27 09:37:47"},{"AttachmentList":[{"name":"原附件","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55883"},{"name":"1","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55884"},{"name":"2","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55885"},{"name":"亿方登录","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55886"},{"name":"招投标算法","url":"http:\/\/localhost:11506\/DownloadFile.ashx?id=55887"}],"bz":"","cbsCode":"W0477","cbsName":"生产服务1407","dz":"地址","frdb":"生产","frdh":"","lxr":"","lxrdh":"18302418581","shxydm":"SCFW1407","ty":0,"ywfw":"","zjsj":"2024-12-27 09:37:39"}]}DataContractJsonSerializer
--------------------------------------------------------------------------------
{"ClientInfo":[{"cbsCode":"W0476","cbsName":"生产服务140701公司","frdb":"公司","frdh":"","lxr":"联系人","lxrdh":"18302418581","dz":"地址","shxydm":"SCFW140701","ywfw":"","fj":null,"bz":"","ty":0,"czsj":"2024-12-27T01:37:47Z","AttachmentList":[{"name":"原附件","url":"http://localhost:11506/DownloadFile.ashx?id=55882"},{"name":"加1附件","url":"http://localhost:11506/DownloadFile.ashx?id=55890"}]},{"cbsCode":"W0477","cbsName":"生产服务1407","frdb":"生产","frdh":"","lxr":"","lxrdh":"18302418581","dz":"地址","shxydm":"SCFW1407","ywfw":"","fj":null,"bz":"","ty":0,"czsj":"2024-12-27T01:37:39Z","AttachmentList":[{"name":"原附件","url":"http://localhost:11506/DownloadFile.ashx?id=55883"},{"name":"1","url":"http://localhost:11506/DownloadFile.ashx?id=55884"},{"name":"2","url":"http://localhost:11506/DownloadFile.ashx?id=55885"},{"name":"亿方登录","url":"http://localhost:11506/DownloadFile.ashx?id=55886"},{"name":"招投标算法","url":"http://localhost:11506/DownloadFile.ashx?id=55887"}]}],"Error":null,"Message":null}AFJSONRequestSerializer
--------------------------------------------------------------------------------
{"ClientInfo":[{"cbsCode":"W0476","cbsName":"生产服务140701公司","frdb":"公司","frdh":"","lxr":"联系人","lxrdh":"18302418581","dz":"地址","shxydm":"SCFW140701","ywfw":"","bz":"","ty":0,"zjsj":"2024-12-27 09:37:47","AttachmentList":[{"name":"原附件","url":"http://localhost:11506/DownloadFile.ashx?id=55882"},{"name":"加1附件","url":"http://localhost:11506/DownloadFile.ashx?id=55890"}]},{"cbsCode":"W0477","cbsName":"生产服务1407","frdb":"生产","frdh":"","lxr":"","lxrdh":"18302418581","dz":"地址","shxydm":"SCFW1407","ywfw":"","bz":"","ty":0,"zjsj":"2024-12-27 09:37:39","AttachmentList":[{"name":"原附件","url":"http://localhost:11506/DownloadFile.ashx?id=55883"},{"name":"1","url":"http://localhost:11506/DownloadFile.ashx?id=55884"},{"name":"2","url":"http://localhost:11506/DownloadFile.ashx?id=55885"},{"name":"亿方登录","url":"http://localhost:11506/DownloadFile.ashx?id=55886"},{"name":"招投标算法","url":"http://localhost:11506/DownloadFile.ashx?id=55887"}]}],"error":null,"message":null}AFNewtonJSONRequestSerializer

为什么 JSON 中需要转义正斜杠

在处理 JSON 数据时,我们经常会遇到一些特殊字符需要进行转义的问题。其中,正斜杠(/)是一种比较特别的字符,有时会被转义为 \/。本文将详细探讨为什么在 JSON 中会存在这种转义,并提供相关的代码示例和解释。

什么是 JSON

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。它基于 JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 的一个子集。JSON 使用文本格式来存储和表示数据。

正斜杠的转义

在 JSON 标准中,并没有强制要求必须对正斜杠(/)进行转义。事实上,大多数情况下,直接使用 "/" 是完全有效的。然而,在某些场景下,会将 / 转义为 \/。这种做法主要是出于历史和安全方面的考虑。

历史原因

在早期的 JavaScript 中,JSON 数据通常用于嵌入到 HTML 中作为 <script> 标签的内容。为了避免与 HTML 的注释结束符(</)冲突,一些开发者会选择将 / 转义为 \/。这样可以确保 JSON 字符串不会被错误地解析为 HTML 注释的结束。

例如,在以下代码中:

<script type="text/javascript">
var data = "{\"url\":\"http://example.com/path\"}";
</script>

如果 URL 中包含 /,可能会导致问题。为了避免这种情况,可以将 JSON 字符串转义为:

<script type="text/javascript">
var data = "{\"url\":\"http:\\/\\/example.com\\/path\"}";
</script>

安全原因

在某些安全上下文中,特别是与 XSS(跨站脚本攻击)相关的场景中,对 / 进行转义可以作为一种防御措施。虽然这不是一个严格的安全机制,但可以减少一些潜在的攻击风险。

JSON 库的行为

不同的 JSON 库在处理正斜杠时可能会有不同的行为。例如,在 JavaScript 中使用 JSON.stringify() 方法时,默认情况下不会对 / 进行转义:

var obj = { url: "http://example.com/path" };
var jsonString = JSON.stringify(obj);
console.log(jsonString); // 输出: {"url":"http://example.com/path"}

然而,某些库或工具可能会提供选项来控制是否对 / 进行转义。例如,在 Node.js 中使用 fast-json-stringify 库时,可以通过配置参数来决定是否转义 /

const fastJson = require('fast-json-stringify');

const schema = {
  type: 'object',
  properties: {
    url: { type: 'string' }
  }
};

const stringify = fastJson(schema, { escapeHtml: true });

const obj = { url: "http://example.com/path" };
const jsonString = stringify(obj);
console.log(jsonString); // 输出: {"url":"http:\\/\\/example.com\\/path"}

手动转义

如果需要手动对 JSON 字符串中的 / 进行转义,可以使用正则表达式来实现。例如,在 JavaScript 中:

var obj = { url: "http://example.com/path" };
var jsonString = JSON.stringify(obj).replace(/\/g, '\\/');
console.log(jsonString); // 输出: {"url":"http:\\/\\/example.com\\/path"}

然而,通常情况下不需要手动进行这种转义,因为大多数现代浏览器和库已经很好地处理了这个问题。

总结

虽然在 JSON 标准中没有强制要求对正斜杠(/)进行转义,但在某些历史和安全场景下,可能会将 / 转义为 \/。这种做法有助于避免与 HTML 注释结束符的冲突,并在某些情况下提供一定的安全性。不同的 JSON 库在处理正斜杠时可能有不同的行为,默认情况下大多数库不会对 / 进行转义。

https://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2

Element content 

When script or style data is the content of an element (SCRIPT and STYLE), the data begins immediately after the element start tag and ends at the first ETAGO ("</") delimiter followed by a name start character ([a-zA-Z]); note that this may not be the element's end tag. Authors should therefore escape "</" within the content. Escape mechanisms are specific to each scripting or style sheet language.

ILLEGAL EXAMPLE:
The following script data incorrectly contains a "</" sequence (as part of "</EM>") before the SCRIPT end tag:

    <SCRIPT type="text/javascript">
      document.write ("<EM>This won't work</EM>")
    </SCRIPT>

In JavaScript, this code can be expressed legally by hiding the ETAGO delimiter before an SGML name start character:

    <SCRIPT type="text/javascript">
      document.write ("<EM>This will work<\/EM>")
    </SCRIPT>

In Tcl, one may accomplish this as follows:

    <SCRIPT type="text/tcl">
      document write "<EM>This will work<\/EM>"
    </SCRIPT>

In VBScript, the problem may be avoided with the Chr() function:

    "<EM>This will work<" & Chr(47) & "EM>"
复制代码
JSON: why are forward slashes escaped?
Asked 15 years, 2 months ago
Modified 1 year, 7 months ago
Viewed 291k times
482

The reason for this "escapes" me.

JSON escapes the forward slash, so a hash {a: "a/b/c"} is serialized as {"a":"a\/b\/c"} instead of {"a":"a/b/c"}.

Why?

javascriptjson
Share
Improve this question
Follow
asked Oct 16, 2009 at 21:54
Jason S's user avatar
Jason S
189k172172 gold badges630630 silver badges995995 bronze badges
4
FWIW I've never seen forward slashes escaped in JSON, I just noticed it with the Java library at code.google.com/p/json-simple – 
Jason S
 CommentedOct 16, 2009 at 22:29
37
PHP's json_encode() escapes forward slashes by default, but has the JSON_UNESCAPED_SLASHES option starting from PHP 5.4.0 (March 2012) – 
Walter Tross
 CommentedJul 1, 2012 at 19:52
12
Here's a PHP code that will not escape every slash, only in '</': echo str_replace('</', '<\/', json_encode($obj, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); – 
rustyx
 CommentedJan 20, 2013 at 13:52 
Does the code include the '</': or does it start at echo? Because starting at echo fails for me. I simply dont get anything. Yes I replaced my $obj for my variable :) – 
marciokoko
 CommentedJul 8, 2013 at 14:58
1
JSON doesn't escape or serialize anything... your JSON serializer does. Which one are you using? – 
Lightness Races in Orbit
 CommentedMay 11, 2017 at 16:31
Add a comment
5 Answers
Sorted by:

Highest score (default)
371

JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required, like Harold L points out:

The JSON spec says you CAN escape forward slash, but you don't have to.

Harold L answered Oct 16 '09 at 21:59

Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out:

This is because HTML does not allow a string inside a <script> tag to contain </, so in case that substring's there, you should escape every forward slash.

Seb answered Oct 16 '09 at 22:00

Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)

Share
Improve this answer
Follow
edited Mar 17, 2023 at 10:46
Bergi's user avatar
Bergi
663k158158 gold badges1k1k silver badges1.5k1.5k bronze badges
answered Oct 16, 2009 at 22:04
Ruben's user avatar
Ruben
15.5k22 gold badges3636 silver badges4545 bronze badges
4
That would be a good thing, escaping just </. Though JSON is not often embedded in script tags anyway. – 
Ruben
 CommentedOct 16, 2009 at 22:20
8
See this blog post for the rationale for the ASP.NET JSON date format: weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx – 
Michiel van Oosterhout
 CommentedDec 18, 2011 at 21:51
36
JSON needs to be replaced because a particular implementation of a JSON serializer outputs some JSON that (while being entirely valid JSON) has some extra characters so it can also be dropped into an HTML script element as a JS literal?! That isn't so much throwing the baby out with the bathwater as throwing the baby out because someone bought him a set of water wings. – 
Quentin
 CommentedJun 1, 2012 at 22:53 
32
What I don't get, is why a JSON serializer would even care where the JSON ends up. On a web page, in an HTTP request, whatever. Let the final renderer do additional encoding, if it needs it. – 
Dan Ross
 CommentedApr 28, 2016 at 5:11
8
@DanRoss And it can. Escaping / is not required, it is allowed, to ease the use of JSON. If you don't want to escape /, then don't. – 
Andreas
 CommentedMay 6, 2016 at 20:56
Show 18 more comments
53

The JSON spec says you CAN escape forward slash, but you don't have to. A reverse solidus must be escaped, but you do not need to escape a solidus. Section 9 says

"All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F."

Share
Improve this answer
Follow
edited May 12, 2023 at 12:04
StayOnTarget's user avatar
StayOnTarget
12.9k1111 gold badges6060 silver badges106106 bronze badges
answered Oct 16, 2009 at 21:59
Harold L's user avatar
Harold L
5,2562929 silver badges2828 bronze badges
Add a comment
28

PHP escapes forward slashes by default which is probably why this appears so commonly. I suspect it's because embedding the string "</script>" inside a <script> tag is considered unsafe.

Example:

<script>
var searchData = <?= json_encode(['searchTerm' => $_GET['search'], ...]) ?>;
// Do something else with the data...
</script>
Based on this code, an attacker could append this to the page's URL:

?search=</script> <some attack code here>
Which, if PHP's protection was not in place, would produce the following HTML:

<script>
var searchData = {"searchTerm":"</script> <some attack code here>"};
...
</script>
Even though the closing script tag is inside a string, it will cause many (most?) browsers to exit the script tag and interpret the items following as valid HTML.

With PHP's protection in place, it will appear instead like this, which will NOT break out of the script tag:

<script>
var searchData = {"searchTerm":"<\/script> <some attack code here>"};
...
</script>
This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES flag but most developers will not use this since the original result is already valid JSON.

Share
Improve this answer
Follow
edited Jul 12, 2022 at 4:00
answered Jan 22, 2018 at 2:30
Simon E.'s user avatar
Simon E.
58.4k1818 gold badges144144 silver badges137137 bronze badges
4
"is considered unsafe" -> it really is unsafe. Exploit: <script>let the = "bodies </script><script>alert("the floor");</script>";</script> Try it, the bodies will alert the floor rather than getting a variable called 'the' with script tags in its value. You can say "then don't embed it in a page", yeah, that's a possible workaround, but a lot of people do this anyway (so let's just make good escape functions because why not) and frankly I understand their point: it would make sense if it were safe to have JSON data with correctly escaped data values in JavaScript. – 
Luc
 CommentedMar 19, 2021 at 13:44 
2
Thanks @Luc - great example of why PHP has opted to escape slashes by default! Functions should be secure by default, and only insecure when you specifically want it that way. – 
Simon E.
 CommentedMar 20, 2021 at 1:12
I beg to differ. PHP shouldn't encode forward slashes by default. If a frontend developer want to echo user inputted value into HTML code, he should realize that it is always very dangerous, whether it is inside <script> or inside a <div>; and he should be the one to take a lot of precautions, by using htmlspecialchars(), for example. On the backend, it is perfectly safe to not escape forward slashes. – 
Daniel Wu
 CommentedAug 23, 2023 at 4:01
@DanielWu Unfortunately many developers are lazy, which is why “secure by defaultis a good strategy. Developers can disable those additional slashes by adding the extra parameter if they understand the consequences. (Also I don’t think htmlspecialchars() will work in this scenario. The slashes are still required.) – 
Simon E.
 CommentedAug 26, 2023 at 0:56
@DanielWu Since (unfortunately!) JSON stems from Javascript (JavaScript Object Notation), it only makes sense that it was originally adapted for use in Javascript. Unfortunately, as with all things related to Javascript, it has gained widespread use in all kinds of places. Unfortunately they are now so widespread that it would be hard to replace them, even if that would be the most sensible thing to do... – 
Magnus
 CommentedAug 6 at 8:19
Add a comment
22

I asked the same question some time ago and had to answer it myself. Here's what I came up with:

It seems, my first thought [that it comes from its JavaScript roots] was correct.

'\/' === '/' in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like \z) not allowed in JSON?

The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.

Share
Improve this answer
Follow
edited Jan 19, 2022 at 10:38
hakre's user avatar
hakre
197k5555 gold badges446446 silver badges853853 bronze badges
answered Mar 16, 2012 at 10:18
Boldewyn's user avatar
Boldewyn
82.7k4545 gold badges159159 silver badges214214 bronze badges
7
A structured data payload delivery mechanism should not be tied to language constructs..as this may change in the future...but this might explain the design decisions if there were any of the JSON creators. – 
user656925
 CommentedJun 1, 2012 at 21:11
2
'\/' === '/' So I don't need to unescape forward slashes when receiving my jsonp? – 
Timmetje
 CommentedFeb 7, 2013 at 9:30 
Add a comment
1

Yes, some JSON utiltiy libraries do it for various good but mostly legacy reasons. But then they should also offer something like setEscapeForwardSlashAlways method to set this behaviour OFF.

In Java, org.codehaus.jettison.json.JSONObject does offer a method called

setEscapeForwardSlashAlways(boolean escapeForwardSlashAlways)

to switch this default behaviour off.

Share
Improve this answer
Follow
answered Oct 10, 2022 at 12:14
Pratap Singh's user avatar
Pratap Singh
41911 gold badge44 silver badges1414 bronze badges

复制代码

 




 

反序列化

 

复制代码
{
"invoice": "500102000000159",
"orderID": "89d5225d-23e8-49c2-9148-872dfd33df45",
"fpzt": null,
"operation": null
}
System.Collections.Generic.Dictionary<string, object> objResult = (System.Collections.Generic.Dictionary<string, object>)new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(xmlResult);
复制代码

 


 

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace GSPWebService
{
    [System.Runtime.Serialization.DataContract(Namespace ="", Name = "result")]
    [Serializable]    
    public class ResponseResult
    {
        /// <summary>
        /// 发生错误时,直接返回错误信息
        /// </summary>
        [XmlElement("error")]
        [System.Runtime.Serialization.DataMember(Name = "error")]
        public string Error
        {
            get;
            set;
        }

        /// <summary>
        /// 调用成功时,返回成功上传多少条记录。
        /// </summary>
        [XmlElement("message")]
        [System.Runtime.Serialization.DataMember(Name = "message")]
        public string Message
        {
            get;
            set;
        }
    }
}
复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GSPWebService
{
    public class WebServiceHelper
    {
        public static ResponseResult uploadStockrecord(DataSet_EquStockrecords dtsResult)
        {
            //string result = new GSPServiceReference.GspWsServicePortTypeClient().uploadStockrecord(dtsResult.GetXml());
            var result = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<result>
    <error>上传失xml格式出错</error>
</result>";

            byte[] byteBuffer = System.Text.Encoding.UTF8.GetBytes(result);
            System.IO.Stream stream = new System.IO.MemoryStream(byteBuffer);
            System.IO.MemoryStream outStream = new System.IO.MemoryStream(8);
            System.Runtime.Serialization.DataContractSerializer serial = new System.Runtime.Serialization.DataContractSerializer(typeof(ResponseResult), "result", "");
            serial.WriteObject(outStream, new ResponseResult() { Message = "OK", Error = "NO"});
            String strObj = System.Text.UTF8Encoding.UTF8.GetString(outStream.GetBuffer());
            var obj = serial.ReadObject(stream);
            stream.Position = 0;
            System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(ResponseResult), 
                new System.Xml.Serialization.XmlRootAttribute("result"));
            
            ResponseResult res = xmlSerializer.Deserialize(stream) as ResponseResult;
            return res;
        }
    }
}
复制代码

 

Newtonsoft.Json vs. System.Text.Json


2023-05-05更新

有懂的没,json对象中 嵌入 json字符串 它规范吗?

对接慧税云API时, 它们返回的JSON数据格式是这样的,复杂类型补双引号包括,就是字符串类型了,

碰到这样的接口,你的类对象相应字段不能定义复杂类型,只能定义string,然后单独解析这个 string,烦人不?算是违反JSON规则不?

复制代码
{
  "businessType":"105",
  "data":"{
      \"code\":\"500\",
      \"message\":\"打印失败\",
      \"data\":{
          \"invoiceCode\":\"1111111\",
          \"invoiceNo\":\"2222222\",
          \"printStatus\":1 
      }
  }"
}
复制代码

 

{"data":"{\""code\"":\""200\"",\""data\"":{\""applyType\"":0,\""dept_code\"":\""\"",\""purchaserBankAccount\"":\""10614901040010974\"",\""exten10\"":\""\"",\""listFlag\"":0,\""purchaserPhone\"":\""13900221111\"",\""createUserName\"":\""宋忠琳\"",\""handlerName\"":\""\"",\""sellerAddress\"":\""66+\"",\""business_code\"":\""\"",\""drewDate\"":1682414622000,\""payee\"":\""\"",\""oldInvoiceNo\"":\""\"",\""logisticsFlag\"":0,\""externalDocumentNo\"":\""638180402188064058\"",\""viewUrl\"":\""\"",\""invoiceType\"":7,\""machineNo\"":\""\"",\""applyTime\"":1682414623000,\""invoiceDrewDate\"":\""2023-04-25 17:23:42\"",\""invoiceNo\"":\""10000000000000002567\"",\""transaction_id\"":\""\"",\""business_name\"":\""\"",\""settlementNo\"":\""JS230425903226\"",\""machineCode\"":\""\"",\""elementCode\"":\""\"",\""taxCode\"":\""\"",\""invoiceCode\"":\""\"",\""purchaserName\"":\""常州优卓自动化科技有限公司\"",\""checkCode\"":\""\"",\""purchaserBankName\"":\""中国农业银行常州金佰支行\"",\""serialNo\"":\""835566689411158016\"",\""xmlUrl\"":\""https://huisuiyun.oss-cn-shanghai.aliyuncs.com/pro/permanent/default/20230425/9e0b24b3-8e89-484e-80cf-a0cf95b341b52320230425/10000000000000002567.zip\"",\""taxRate\"":\""0.130\"",\""emailStatus\"":0,\""sellerTaxNo\"":\""986565639\"",\""purchaserEmail\"":\""wellingsok@hotmail.com\"",\""purchaserTaxNo\"":\""91320411323669980M\"",\""carLogId\"":\""\"",\""detailList\"":[{\""invoiceLineType\"":0,\""discountAmount\"":0.00,\""createUserName\"":\""宋忠琳\"",\""categoryName\"":\""\"",\""extend10\"":\""\"",\""id\"":835566690376060929,\""goodsName\"":\""软件\"",\""revenueCode\"":\""1060301020200000000\"",\""unitPrice\"":10.000000000000000,\""amount\"":10.00,\""quantity\"":1.000000000000000,\""goodsTypeCode\"":\""0\"",\""taxPreType\"":0,\""zeroTax\"":0,\""specification\"":\""xxl\"",\""extend7\"":\""\"",\""xh\"":\""\"",\""extend6\"":\""\"",\""taxRate\"":0.130,\""extend9\"":\""\"",\""unit\"":\""个\"",\""extend8\"":\""\"",\""deduction\"":0.00,\""extend3\"":\""\"",\""extend2\"":\""\"",\""extend5\"":\""\"",\""extend4\"":\""\"",\""revenueVersion\"":\""0.00\"",\""taxPre\"":1,\""extend1\"":\""\"",\""goodsCode\"":\""\"",\""amountWithTax\"":11.30,\""shortName\"":\""*软件*\"",\""taxAmount\"":1.30}],\""specialFlag\"":0,\""taxAmount\"":1.30,\""sellerBankName\"":\""56563\"",\""resultMatchFlag\"":0,\""VoucherType\"":\""\"",\""exten4\"":\""\"",\""exten5\"":\""\"",\""exten2\"":\""\"",\""exten3\"":\""\"",\""matchFlag\"":0,\""exten8\"":\""\"",\""exten9\"":\""\"",\""handlerCertificateCode\"":\""\"",\""oldInvoiceCode\"":\""\"",\""exten6\"":\""\"",\""exten7\"":\""\"",\""signStatus\"":0,\""sellerName\"":\""虚拟通道023\"",\""remark\"":\""备注0\"",\""exten1\"":\""\"",\""purchaserAddress\"":\""常州市钟楼区锦江丽都花园1幢-8号2楼\"",\""sid\"":835566689251774464,\""pdfUrl\"":\""https://huisuiyun.oss-cn-shanghai.aliyuncs.com/pro/permanent/default/20230425/24e915ab-6ae5-45bc-98a8-1e3c3ec629a718920230425/10000000000000002567.pdf\"",\""billingType\"":0,\""specificElements\"":[],\""phoneStatus\"":0,\""sellerTel\"":\""1\"",\""redApplicationNo\"":\""\"",\""amount\"":10.00,\""ciphertext\"":\""\"",\""handlerCertificateNo\"":\""\"",\""handlerTaxNo\"":\""\"",\""applyMsg\"":\""\"",\""drawer\"":\""023测试\"",\""dept_name\"":\""\"",\""purchaserTel\"":\""0519-88029938\"",\""reviewer\"":\""\"",\""lockFlag\"":0,\""ofdUrl\"":\""https://huisuiyun.oss-cn-shanghai.aliyuncs.com/pro/permanent/default/20230425/ed1bff2a-ee5a-4008-8431-9a17f94efdad11820230425/10000000000000002567.ofd\"",\""sellerBankAccount\"":\""1\"",\""amountWithTax\"":11.30,\""invoiceStatus\"":10},\""message\"":\""开具成功\"",\""serialNo\"":\""638180402188064058\""}","businessType":"102"}

 


复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BarCodeParseIdentityLib.Util
{
    public class WareInfo
    {

        public String dtExp
        {
            set;
            get;
        }

        public String dtSterilizeDate
        {
            set;
            get;
        }

        public String dtProductDate
        {
            set;
            get;
        }

        [System.Runtime.Serialization.IgnoreDataMember]
        public String strMemo
        {
            set;
            get;
        }

        public String strSN
        {
            set;
            get;
        }

        public String strBatchNo
        {
            set;
            get;
        }

        public String strSterilizeNo
        {
            set;
            get;
        }

        public String barCode
        {
            set;
            get;
        }

        [System.Runtime.Serialization.IgnoreDataMember]
        public String strWareCode
        {
            set;
            get;
        }

        public String cUniqueCode
        {
            set;
            get;
        }
    }
}
复制代码
复制代码

/// <summary>
/// 不输出的字段可以覆盖
/// </summary>
public class SendFpInfoRequest_NoRemark : SendFpInfoRequest
{
/// <summary>
///
/// </summary>
[ScriptIgnore]
public new string remark
{
set;
get;
}
}


///
<summary> /// DataContract JsonSerializer,缺点是需要序列化的对象继承层级不能出现重复的属性 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string getJSONStringify<T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer jsonSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); var stream = new MemoryStream(); jsonSerializer.WriteObject(stream, obj); stream.Position = 0; StreamReader streamResult = new StreamReader(stream, Encoding.GetEncoding("utf-8")); string json = streamResult.ReadToEnd(); return json; } /// <summary> /// JavaScriptSerializer /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string getJSONByJavascriptSerializer(object obj) { JavaScriptSerializer jsonSerial = new JavaScriptSerializer(); string strJson = jsonSerial.Serialize(obj); return strJson; }
复制代码

 

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace BarCodeParseIdentityLib.Util
{
[Serializable] [DataContract] 被标记这个了,那么就只有datamember属性才会被序列化
public class WareInfo { [DataMember(Name = "失效日期", EmitDefaultValue = false)] public String dtExp { set; get; } [DataMember(Name = "灭菌效期", EmitDefaultValue = false)] public String dtSterilizeDate { set; get; } [DataMember(Name = "生产日期", EmitDefaultValue = false)] public String dtProductDate { set; get; } [System.Runtime.Serialization.IgnoreDataMember] public String strMemo { set; get; } [DataMember(Name = "序列号", EmitDefaultValue = false)] public String strSN { set; get; } [DataMember(Name = "批号", EmitDefaultValue = false)] public String strBatchNo { set; get; } [DataMember(Name = "灭菌批号", EmitDefaultValue = false)] public String strSterilizeNo { set; get; } [DataMember(Name = "商品编码", EmitDefaultValue = false)] public String barCode { set; get; }
[System.Web.Script.Serialization.ScriptIgnore] //JavascriptSerializer System.Web.Extensions.dll [System.Runtime.Serialization.IgnoreDataMember]//DataContract System.Runtime.Serialization.dll
[System.Xml.Serialization.XmlIgnore]
[NonSerialized] //Serialized
public String strWareCode { set; get; } public String cUniqueCode { set; get; } } }
复制代码

 


 

posted on   不及格的程序员-八神  阅读(376)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示