简体   繁体   中英

Is there a way to serialize / deserialize an object to a string in C#?

Is there any kind of text serializer in C#, which is able to serialize / deserialize this shortened example...

public class Record
{
    // Letters 1-4
    public string Identifier { get; set; }

    // Letters 5-12
    public string ProcessAbbreviation { get; set; }

    // Letters 13-16
    public string Name { get; set; }
}

... into this string?

AAAABBBB    CCCC

Note, that the string must contain whitespaces if the property hasn't the desired length.

Although it must be possible to serialize / deserialize into the other direction, eg string into object.

I've already tried to find something, which suits my requirement, but I couldn't find anything.

I highly appreciate any kind of help, cheers: :)

There's not going to be an existing library to do this, but it's very easy to write your own serialisation and deserialisation:

public class Record
{
    // Letters 1-4
    public string Identifier { get; set; }

    // Letters 5-12
    public string ProcessAbbreviation { get; set; }

    // Letters 13-16
    public string Name { get; set; }

    public string Serialize()
    {
        return $"{Identifier, -4}{ProcessAbbreviation, -8}{Name, -4}";
    }

    public static Record Deserialize(string input)
    {
        if (input is not { Length: 16 })
            throw new ArgumentException("input must be 16 characters long");

        return new Record
        {
            Identifier          = input.Substring( 0, 4).Trim(),
            ProcessAbbreviation = input.Substring( 4, 8).Trim(),
            Name                = input.Substring(12, 4).Trim()
        };
    }
}

Test code:

public static void Main()
{
    var rec = new Record { Identifier = "AAAA", ProcessAbbreviation = "BBBB", Name = "CCCC" };

    var serialised = rec.Serialize();
    Console.WriteLine("|" + serialised + "|");

    var r = Record.Deserialize(serialised);

    Console.WriteLine($"|{r.Identifier}|{r.ProcessAbbreviation}|{r.Name}|");
}

Try it on DotNetFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM