我正在使用 WCF,我的一些方法返回一个类,当转换为 JSON 时,生成一个如下所示的对象:
{
"__type": "Data:#MyNamespace.Model"
"Dado_x0020_1": "1"
"Dado_x0020_2": "2"
"Dado_x0020_3": "3"
}
我清楚地记得以前不是这样的,WCF不会替换“_x0020_”的空格字符。问题是我不知道我的代码做了什么改变来实现这一点。我不记得更改会导致此问题的任何配置。有什么想法吗?
这是我类(class)的代码。这只是一种允许具有可变属性名称和计数的对象的方法:
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;
}
}
}
}
最佳答案
它是 WCF 的 DataContractJsonSerializer添加那些 _x0020_
字符。如果您想将输出用于 WCF 通信之外的其他用途,则需要使用不同的 json 序列化程序(如 json.net)。
但是,如果您将 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 上下文之外没有多大用处。
关于c# - 如何避免替换 "_x0020_"的空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25364247/