如何避免为“_x0020_"”替换空格
本文关键字:替换 空格 quot x0020 何避免 | 更新日期: 2023-09-27 18:18:24
我正在使用WCF和我的一些方法返回一个类,当转换为JSON时,生成这样的对象:
{
"__type": "Data:#MyNamespace.Model"
"Dado_x0020_1": "1"
"Dado_x0020_2": "2"
"Dado_x0020_3": "3"
}
我清楚地记得以前不是这样的,WCF不会替换"_x0020_"的空格字符。问题是我不知道在我的代码中做了什么改变来实现这一点。我不记得改变任何配置会导致这种情况。什么好主意吗?
这是我的类代码。它只是一种允许对象具有可变属性名称和计数的方法:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace MyNamespace.Model
{
[Serializable]
public class Data : ISerializable
{
internal Dictionary<string, object> Attributes { get; set; }
public Data()
{
Attributes = new Dictionary<string, object>();
}
protected Data(SerializationInfo info, StreamingContext context)
: this()
{
SerializationInfoEnumerator e = info.GetEnumerator();
while (e.MoveNext())
{
Attributes[e.Name] = e.Value;
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (string key in Attributes.Keys)
{
info.AddValue(key, Attributes[key]);
}
}
public void Add(string key, object value)
{
Attributes.Add(key, value);
}
public object this[string index]
{
set { Attributes[index] = value; }
get
{
if (Attributes.ContainsKey(index))
return Attributes[index];
else
return null;
}
}
}
}
添加这些_x0020_
字符的是WCF的DataContractJsonSerializer。你需要使用不同的json序列化器(如json.net),如果你想使用输出的其他东西,而不是WCF通信。
然而,如果您将Data
类更改为如下内容:
[DataContract]
public class Data
{
public Data()
{
Attributes = new Dictionary<string, object>();
}
[DataMember]
public Dictionary<string, object> Attributes { get; set; }
[IgnoreDataMember]
public object this[string index]
{
set { Attributes[index] = value; }
get
{
if (Attributes.ContainsKey(index))
return Attributes[index];
else
return null;
}
}
}
然后是下面的WCF序列化:
class Program
{
static void Main(string[] args)
{
var data = new Data();
data["Dado 1"] = 1;
data["Dado 2"] = 2;
data["Dado 3"] = 3;
var dcjs = new DataContractJsonSerializer(typeof(Data));
MemoryStream stream1 = new MemoryStream();
dcjs.WriteObject(stream1, data);
stream1.Seek(0, SeekOrigin.Begin);
var json3 = new StreamReader(stream1).ReadToEnd();
}
}
将产生如下结果:
{
"Attributes": [
{
"Key": "Dado 1",
"Value": 1
},
{
"Key": "Dado 2",
"Value": 2
},
{
"Key": "Dado 3",
"Value": 3
}
]
}
但是我仍然不认为它在WCF上下文之外有多大用处