Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.Net serialize XML to JSON camel case

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()
});
like image 447
Homer Avatar asked Mar 05 '13 22:03

Homer


1 Answers

Make a model of your XML data

example

public class MyClass
    {
        [JsonProperty("@SomeXMLProperty")]
        public string MyString{ get; set; }
    }

then deserialize XML to your model

XDocument xmlDocument = XDocument.Parse(xmlData);
string jsonData = JsonConvert.SerializeXNode(xmlDocument);
var myClass = JsonConvert.DeserializeObject<MyClass>(jsonData); 

then just use CamelCasePropertyNamesContractResolver and Formatting.Indented

string json = JsonConvert.SerializeObject(rootObject,
                              Newtonsoft.Json.Formatting.Indented,
                              new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() });  

UPDATE:

The first solution is simple and clean (no need to write custom resolvers etc.) this is just for removing @ sign

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

If anybody knows a better solution for both cases then the first it would be nice to look at it.

WebAPI addition

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; 
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
like image 187
Matija Grcic Avatar answered Nov 14 '22 21:11

Matija Grcic