如何获取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()
});
创建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。缩进
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();