如何让JSON.Net将我的XML序列化为驼峰案例JSON而没有“@”?
这是我现在所拥有的,但是它会在属性之前预设@并且不会出现这种情况......
XmlDocument doc = new XmlDocument();
doc.LoadXml(myXmlString);
string jsonText = Newtonsoft.Json.JsonConvert.SerializeObject(doc, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
答案 0 :(得分:10)
制作XML数据模型
例如
public class MyClass
{
[JsonProperty("@SomeXMLProperty")]
public string MyString{ get; set; }
}
然后将XML反序列化为您的模型
XDocument xmlDocument = XDocument.Parse(xmlData);
string jsonData = JsonConvert.SerializeXNode(xmlDocument);
var myClass = JsonConvert.DeserializeObject<MyClass>(jsonData);
然后只使用 CamelCasePropertyNamesContractResolver 和 Formatting.Indented
string json = JsonConvert.SerializeObject(rootObject,
Newtonsoft.Json.Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() });
<强>更新强>
第一个解决方案简单而干净(无需编写自定义解析器等)这只是用于删除@符号
var xml = new XmlDocument();
xml.XmlResolver = null;
xml.Load("yourfilehere");
var json = JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.Indented);
var withoutATSign = System.Text.RegularExpressions.Regex.Replace(json, "(?<=\")(@)(?!.*\":\\s )", String.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
如果有人知道两个案例的更好的解决方案,那么第一个看它会很好。
添加WebAPI
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();