Json驼峰套管属性

时间:2018-04-06 02:24:26

标签: c# serialization json.net

https://dotnetfiddle.net/R96sPn

我正在尝试创建AddJsonObject,以使name的{​​{1}}服从External.AddParameter

所设置的ContractRevolver

在下面的示例中,它是驼峰外壳,但正如您所看到的那样,输出不是驼峰式的。更改ContractResolver应该有效地确定External.Serialize参数的格式。无法向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"
]

此演示使用JSON.net和CamelCase展示Serialize,但AddJsonObject应独立于他们使用的json序列化程序或格式化。这个例子只展示了一个非常重要的例子。

我最初的尝试包括将对象包装到父对象中。然后,childProduct : { "expiry": "0001-01-01T00:00:00" } name : "Apple" expiry : "2008-12-28T00:00:00" sizes : [ "small", "big" ] 包装器对象以某种方式将结果反馈到External.Serialize(),以使AddParameter成为序列化的输出 - 无法使其正常工作。

2 个答案:

答案 0 :(得分:0)

将ContractResolver(ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver())初始化为

的更改行
ContractResolver = new DefaultContractResolver
{
    NamingStrategy = new CamelCaseNamingStrategy()
};

答案 1 :(得分:0)

好的,我有一个有效的解决方案,但我会推迟更聪明的答案

public void AddJsonObject(object obj)
{
    var jsonObj = JObject.Parse(External.Serialize(obj));
    foreach (var property in jsonObj.Properties())
    {
        External.AddParameter(property.Name, External.Serialize( property.Value));
    }
}