(De)serialize custom data in a gh file

Apparently, we can’t serialize data in a gh file, because saving overwrites the file, losing the data artifically added. Is this correct?

Is there any way to get this? I need to store data without being visible to the user, and I prefer it to be per document rather than per gh settings, because it can be a lot of data.

Thank you!

Example:

GH_Archive arc = new GH_Archive();
arc.ReadFromFile(GrasshopperDocument.FilePath);
Prueba p = new Prueba(23);
arc.AppendObject(p, "miPrueba");

public class Prueba : GH_IO.GH_ISerializable {
public int valor;
public Prueba(int v){valor = v;}

public bool Read(GH_IReader reader)
{
  valor = reader.GetInt32("valor");
  return true;
}

public bool Write(GH_IWriter writer)
{
  writer.SetInt32("valor", valor);
  return true;
}
  }

This writes to the file. Then saving the document, I lose that data. Am I doing something wrong?

Correct, every time Grasshopper saves a file it will create all the file data from scratch. Any data you inject into a Grasshopper_IO archive outside of the normal process will be lost.

The only way to include data in an archive is to write it when the archive itself is written. This means you almost certainly have to put a component that does this custom writing on the canvas. Is that a solution for you, or do you really need to include this data without adding objects?

Pity.
No objects on the canvas.
I have thought about create a component programmatically just before closing the document, and when I opened the document I accessed the data and deleted the component. But I think it’s a terrible solution. Any suggestions?
Thanks for your help.

It’s the only solution I think if you do not want to add something more persistent, although I don’t understand how you know a save is about to begin.

I created RH-42540 so I’ll remember to make this easier in the future.

Okay, thank you. A list of metadata/user data within the document would be sufficient for me in this case.

And what do you consider best, the previous solution or create a component where to store my data without visualization and interaction? In that case, inheriting from GH_DocumentObject is enough?

Should be. Grasshopper isn’t set up to have ‘ghost’ objects, so you’ll have to create attributes that make it invisible to both the user and the application. I.e. you don’t want your object to disappear is someone uses Select All + Delete. You’ll also have to handle the AddedToDocument etc. methods to prevent more than one of your special objects.

Try the attached as a starting point.

io_object.cs (5.2 KB)

:smiley:
Really appreciated, good solution. I didn’t trust myself to do this right!

Document metadata that behaves similar to Rhino.Doc.Strings would be fantastic!

RH-42602 is now in effect y’all.

2 Likes