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

1 Answer 1

10

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();
Sign up to request clarification or add additional context in comments.

2 Comments

are you saying to Serialize then Deserialize then Serialize again?
Yes the first solution is the cleanest. Are you maybe using WebAPI and in need of the camel case? If so, then it's just two lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.