8

How do I get JSON.Net to serialize my XML to camel case JSON and without the "@"?

this is what I currently have but it prepends @ to the properties and does not camel case...

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()
});
4

1 回答 1

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); 

然后只需使用CamelCasePropertyNamesContractResolverFormatting.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();
于 2013-03-05T23:24:14.253 回答