我正在使用Web Api 2.
我的WebApiConfig中有以下代码:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration
.Formatters
.JsonFormatter
.SerializerSettings
.ContractResolver = new LowerCaseContractResolver();
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
与LowerCaseContractResolver相关的部分是指:
public class LowerCaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
然后,我希望将带有大写名称的c#对象转换为JArray中的小写JObject,如下所示:
string treeString = JsonConvert.SerializeObject(TreeViewLabelWithChildren);
JObject treeJObject = JObject.Parse(treeString);
JArray TreeJarray = new JArray();
TreeJarray.Add(treeJObject);
return TreeJarray;
返回的JArray仍包含大写名称。我已尝试在Application_Start()中应用自定义合约解析程序。我可以通过内联应用自定义合约解析器来实现这一点,但是想要一种全局的方式来设置它。内联工作:
var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowerCaseContractResolver();
string treeString = JsonConvert.SerializeObject(TreeViewLabelWithChildren, Formatting.Indented, settings);
答案 0 :(得分:0)
我刚刚找到答案。我不需要返回JArray,如果我只返回一个包含我的C#对象的数组,那么Web Api 2将完成剩下的工作。