Search code examples
c#json.netmetadata-extractor

Serialize and de-serialize metadata-extractor-dotnet


I'm serializing the metadata from an uploaded image so that I'm able to persist it in the database.

It's possible to serialize the data using Custom JsonConverter from Newtonsoft (JSON.NET) - however de-serializing it fails:

(IReadOnlyList<MetadataExtractor.Directory>)JsonConvert.DeserializeObject(metadata)

With this exception:

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

Additional information: Could not create an instance of type MetadataExtractor.Directory. Type is an interface or abstract class and cannot be instantiated. Path '[0].Name', line 1, position 9.

Since the list of directories may vary depending on the specific object, I doubt it's trivial to serialize/de-serialize the directories individually.

Any simple suggestions as how to save only the metadata part of an uploaded image into a form that's possible to re-use later?


Solution

  • Metadata Extractor doesn't support serialisation, although there is an active issue on the Java version that's discussing this at the moment.

    Part of the problem there applies here too -- it all depends upon why you want to serialise the data. If you need it in full fidelity, it's considerably more work than if you just want to save/restore a few property descriptions.

    You could write descriptions as XML using something like:

    var doc = new XDocument(
        new XElement("Metadata",
            directories.Select(directory =>
                new XElement("Directory",
                    new XAttribute("Name", directory.Name),
                    directory.Tags.Select(tag =>
                        new XElement("Tag",
                            new XAttribute("Id", tag.Type.ToString("X"),
                            new XAttribute("Name", tag.Name),
                            tag.Description))))));
    

    This would produce XML resembling:

    <Metadata>
      <Directory Name="Exif IFD0">
        <Tag Id="10F" Name="Make">NIKON</Tag>
        <Tag Id="110" Name="Model">COOLPIX P340</Tag>
        ...