Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize .Net object to json, controlled using xml attributes

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 to use the existing Xml attributes.

public class world{
  [XmlIgnore]
  public int ignoreMe{ get; }

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

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

becomes

{
  "foo":0,
  "marco":0
}
like image 276
Iain Sproat Avatar asked Jan 14 '11 00:01

Iain Sproat


People also ask

How do you serialize and deserialize an object in C# using JSON?

It returns JSON data in string format. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data.

What is XML serialization?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

How do I serialize a JSON file?

To write JSON to a string or to a file, call the JsonSerializer. Serialize method. The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.

Which of the following attribute controls XML serialization of the attribute target as an XML root element?

XmlRootAttribute Class (System.Xml.Serialization) Controls XML serialization of the attribute target as an XML root element.


1 Answers

Use [JsonProperty(PropertyName="foo")] Attribute and set the PropertyName.

like image 133
Aliostad Avatar answered Sep 21 '22 14:09

Aliostad