为什么我的JSON不是camelCase?

时间:2018-03-08 10:51:41

标签: json.net

我正在尝试使用Json.net输出Json,通过构建动态然后调用JsonConvert.Serialize()。

问题是我的_camelCase合约解析程序不受尊重,输出不是驼峰

private JsonSerializerSettings _camelCase = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var myObj = new { Prop = "val"};
var myObj2 = new { Prop = "val" };
var objOut = JsonConvert.SerializeObject(myObj, _camelCase);
// {"prop":"val"}
// No problem

// now, a list
var list = new List<object> { myObj, myObj2 };
var listOut = JsonConvert.SerializeObject(list, _camelCase);
// [{"prop":"val"},{"prop":"val"}]
// no problem

// now, put my list in a dynamic
dynamic myDynamic = new JObject();
myDynamic.List = JArray.FromObject(list);
var dynamicOut = JsonConvert.SerializeObject(myDynamic, _camelCase);
// {"List":[{"Prop":"val"},{"Prop":"val"}]}
// PROBLEM! _camelCase is not respected

谁能告诉我这里发生了什么?

1 个答案:

答案 0 :(得分:0)

好的,以防这对任何人都有用...计数的序列化设置不是提供给 def __str__(self): return json.dumps(self.data) 的设置,而是用于呼叫JsonConvert.Serialize()的设置。所以我需要用合约解析器创建一个序列化器......

JArray.FromObject()

...然后将其用于private JsonSerializerSettings _camelCase = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; private JsonSerializer _camelCaseSerializer = JsonSerializer.Create(_camelCase); ...

FromObject()

我也可以像这样更改默认设置......

myDynamic.List = JArray.FromObject(list, _camelCaseSerializer );

......但我缺乏勇气: - )