【发布时间】:2020-09-01 04:43:19
【问题描述】:
我有一个名为 _Numeric 的 C# 类,因为不允许使用数字值。我想将其序列化为 JSON,但将 _Numeric 替换为 JSON 键中的数字。
如何编写一些自定义 JSON
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Web.Script.Serialization;
class TestNumeric
{
public InnerNumeric innerNumeric;
public string name;
public TestNumeric()
{
name = "Test Name";
innerNumeric = new InnerNumeric
{
_22 = new _22
{
value = "value _22"
},
someClass = new SomeClass {
value = "some Class value"
}
};
}
public class InnerNumeric
{
public _22 _22;
public SomeClass someClass;
}
public class _22
{
public string value;
}
public class SomeClass
{
public string value;
}
static void Main(string[] args)
{
TestNumeric data = new TestNumeric();
string json = new JavaScriptSerializer().Serialize(data);
Console.WriteLine(jsonString);
}
}
JSON 输出是
{
"innerNumeric": {
"_22": {
"value": "value _22"
},
"someClass": {
"value": "some Class value"
}
},
"name": "Test Name"
}
如何通过将 _22 替换为自定义名称(例如 22)来将其翻译成 22
{
"innerNumeric": {
"22": {
"value": "value _22"
},
"someClass": {
"value": "some Class value"
}
},
"name": "Test Name"
}
使用 Newtonsoft.Json 包我们可以添加[JsonProperty("22")],如何与来自 (System.Web.Script.Serialization) 的 JavaScriptSerializer 实现相同的功能?
【问题讨论】:
-
所以你想在序列化的时候改属性名吧?
-
是的,使用 System.Web.Script.Serialization。