2013-03-05 63 views
6

如何讓JSON.Net將我的XML序列化爲駝峯案例JSON並且沒有「@」?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() 
}); 

回答

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

UPDATE:

第一個解決方案是簡單和乾淨(無需編寫自定義解析器等),這只是爲了去除@符號

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(); 
+0

你說,以序列化反序列化,然後再次序列化? – Homer 2013-03-06 14:10:40

+0

是的,第一個解決方案是最乾淨的。您是否可能使用WebAPI並需要駱駝案例?如果是這樣,那麼它只是兩條線。 – 2013-03-06 15:43:41