How to serialize C # objects to a JSON or XML file

4

I am working with a hospital system and I would like to know how I could export the information of my objects to files with a readable format such as JSON or XML , to be used as input to another program that processes them.

These are my classes:

public class Patient
{
    public string PatienName { get; set; }
    public int Age { get; set; }
    public char Sex { get; set; }
    public string Address { get; set; }
    public Illness Illness { get; set; }

    public Bed Bed { get; set; }
}

public class Bed
{
    public int BedNumber { get; set; }
    public string Aisle { get; set; }
}

public class Illness
{
    public IllnessType Type { get; set; }
    public string IllnessName { get; set; }
}

public class IllnessType
{
    public string IllnessTypeName { get; set; }
    public string Severity { get; set; }
}
    
asked by Erick 10.02.2016 в 23:36
source

5 answers

1

Here is an answer on how to convert class code with XML.

using System.Xml.Serialization;
using System.IO;

class Program
    {
        static void Main(string[] args)
        {
            Patient NewPatient = new Patient()
            {
                Age = 35,
                Address = "Apple red #159",
                Bed = new Bed()
                {
                    Aisle = "54A",
                     BedNumber = 145,

                },
                Illness = new Illness()
                {
                    IllnessName = "Stomach ache",
                     Type = new IllnessType() 
                     { 
                       IllnessTypeName= "Stomach ache type",
                        Severity = "Chronic",
                     },

                },
                 PatienName = "Marisela Smith",
                  Sex = 'F',

            };

            StreamWriter MyFile = new StreamWriter(@"D:\XML.txt");

            XmlSerializer Serializer = new XmlSerializer(typeof(Patient));
            Serializer.Serialize(MyFile,NewPatient);
        }
    }
    
answered by 11.02.2016 / 20:51
source
7

If you use JSON.NET (which you should probably, because it is very useful and easy to use when using JSON), you could create generic lists of your classes and then serialize them to JSON files; for example:

List<Patient> patientList = new List<Patient>();
Patient p = new Patient();
p.PatienName = "Helen Keller";
p.Age = 136;
p.Sex = 'F';
. . .
patientList.Add(p);
. . .
// Entonces, después añadir los pacientes a la lista, los guardas así:    
var jsonPatientList = JsonConvert.SerializeObject(patientList);
System.IO.File.WriteAllText(@"C:\Cualquiera\patients.json", patientList);

In a similar way you can do it with the rest of the classes.

    
answered by 10.02.2016 в 23:47
2

If you want Xml try using System.Xml.Serialization

public static void Guardar(Patient paciente,  String ruta) {
    try
    {

        XmlSerializer serializer = new XmlSerializer(typeof(Patient));

        FileStream fStream = File.Open(ruta , FileMode.Create);

        serializer.Serialize(fStream, paciente);

        fStream.Close();

    }
    catch (Exception e)
    {
    }

}

Or a generic one for all your classes used T (Generic methods)

public static void Guadar<T>(T data,  String url) {
    try
    {


        XmlSerializer serializer = new XmlSerializer(typeof(T));

        FileStream fStream = File.Open(url , FileMode.Create);

        serializer.Serialize(fStream, data);

        fStream.Close();

    }
    catch (Exception e)
    {
    }

}
    
answered by 10.02.2016 в 23:55
0

Adding the response of @ B.ClayShannon , here is a way to convert objects to XML using .Net , no additional frameworks, but you do need to add the dependency to System.XML :

public static string Serialize(object item, bool removeNamespace = true)
{
    if (item == null)
        return null;
    var stringBuilder = new StringBuilder();
    var itemType = item.GetType();
    //remueve "lo.que.sea.el.namespace.de.tu" del nombre completo de la clase: lo.que.sea.el.namespace.de.tu.ClaseConDatos
    if (removeNamespace)
    {
        var xns = new XmlSerializerNamespaces();
        xns.Add(String.Empty, String.Empty);
        new XmlSerializer(itemType).Serialize(new StringWriter(stringBuilder), item, xns);
    }
    else
    {
        new XmlSerializer(itemType).Serialize(new StringWriter(stringBuilder), item);
    }
    return stringBuilder.ToString();
}

Once obtained as a string, you can save it to a file via

System.IO.File.WriteAllLines(ruta, cadenaXml);

And in case you need to deserialize it:

public static T getObjectOfXml<T>(string xmlInput, Type[] extraTypes)
{
    //Parser xml request to object
    StringReader stream = null;
    XmlTextReader reader = null;
    T returnedXmlClass = default(T);

    try
    {
        // serialise to object
        XmlSerializer serializer = new XmlSerializer(typeof(T), extraTypes);
        stream = new StringReader(xmlInput); // read xml data
        reader = new XmlTextReader(stream);  // create reader
        // covert reader to object
        returnedXmlClass = (T)serializer.Deserialize(reader);
    }
    catch
    {
        returnedXmlClass = default(T);
    }
    finally
    {
        if (stream != null) stream.Close();
        if (reader != null) reader.Close();
    }

    //Return object
    return returnedXmlClass;
}
    
answered by 10.02.2016 в 23:55
0

If you want to convert your objeto to xml with the following function, it is very easy and understandable:

public static string GetXMLFromObject(object o) {
   try {
     XmlSerializer serializer = new XmlSerializer(o.GetType());
     StringWriter sw = new StringWriter();
     XmlTextWriter tw = new XmlTextWriter(sw);
     serializer.Serialize(tw, o);
     return sw.ToString();
   } catch (Exception ex) {
     //Handle Exception Code
   } finally {
     sw.close();
     tw.close();
   }
 }

To the method I only send your objeto and you will return a string in xml format. Just remember to add the following using to the class where you are going to add the method.

using System.Web.Script.Serialization;
using System.Xml.Serialization;

I hope you find it useful.

I'll place the link where Take it out, right there you will find how to parse xml to objeto .

    
answered by 11.02.2016 в 02:18