Serialize .Net object to json, controlled using xml attributes

Posted by sprocketonline on Stack Overflow See other posts from Stack Overflow or by sprocketonline
Published on 2011-01-14T00:18:16Z Indexed on 2011/01/14 0:53 UTC
Read the original article Hit count: 697

Filed under:
|
|

I have a .Net object which I've been serializing to Xml and is decorated with Xml attributes. I would now like to serialize the same object to Json, preferably using the Newtonsoft Json.Net library.

I'd like to go directly from the .Net object in memory to a Json string (without serializing to Xml first). I do not wish to add any Json attributes to the class, but instead would like for the Json serializer use the existing Xml attributes.

[XmlRoot("hello")]
public class world{
    [XmlIgnore]
    public int ignoreMe{ get; }

    [XmlElement("foo")]
    public int bar{ get; }

    [XmlElement("marco")]
    public int polo{ get; }
}

becomes

"hello":{
    "foo":0,
    "marco":0
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about xml-serialization