【发布时间】:2018-04-06 02:24:25
【问题描述】:
https://dotnetfiddle.net/R96sPn
我正在尝试创建 AddJsonObject 以使 External.AddParameter 的 name 服从为 External.Serialize 设置的 ContractRevolver 的任何内容
在下面的示例中,它是驼峰式的,但正如您所看到的,输出不是驼峰式的。更改 ContractResolver 应该有效地确定 name 参数的格式。 External类不能添加额外代码
这是一个我无法修改的类:
public static class External
{
public static string Serialize(object obj)
{
JsonSerializer ser = new JsonSerializer{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
using (StringWriter stringWriter = new StringWriter())
{
using (JsonTextWriter jsonTextWriter = new JsonTextWriter((TextWriter)stringWriter))
{
jsonTextWriter.Formatting = Formatting.Indented;
jsonTextWriter.QuoteChar = '"';
ser.Serialize((JsonWriter)jsonTextWriter, obj);
return stringWriter.ToString();
}
}
}
public static void AddParameter(string name, string str)
{
Console.WriteLine(name + " : " + str);
}
}
只是示例类:
public class Product { public Product ChildProduct { get; set; } public string Name { get; set; } public DateTime Expiry { get; set; } public string[] Sizes { get; set; } }
主要:
public class Program
{
public void AddJsonObject(object obj)
{
foreach (var property in obj.GetType().GetProperties())
{
var propValue = property.GetValue(obj, null);
External.AddParameter(property.Name, External.Serialize(propValue));
}
}
public void Main()
{
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[]{"small", "big"};
product.ChildProduct = new Product();
AddJsonObject(product);
}
}
输出:
ChildProduct : {
"expiry": "0001-01-01T00:00:00"
}
Name : "Apple"
Expiry : "2008-12-28T00:00:00"
Sizes : [
"small",
"big"
]
期望的输出:
childProduct : {
"expiry": "0001-01-01T00:00:00"
}
name : "Apple"
expiry : "2008-12-28T00:00:00"
sizes : [
"small",
"big"
]
这个演示展示了使用 JSON.net 和 CamelCase 进行序列化,但 AddJsonObject 应该独立于他们使用的 json 序列化器或格式。这个例子只是展示了一个不平凡的例子。
我最初的尝试包括将对象包装到父对象中。 External.Serialize() 包装器对象然后以某种方式将结果输入到 AddParameter 使得 name 是序列化的输出 - 无法让它正常工作。
【问题讨论】:
标签: c# serialization json.net