I am trying to serialize a Model as JSON-LD and store it in a string variable using RDF4J.
My code looks like this:
public void storeAsString(Model model) {
StringWriter stringWriter = new StringWriter();
RDFWriter rdfWriter = Rio.createWriter(RDFFormat.JSONLD, stringWriter);
rdfWriter.getWriterConfig().set(JSONLDSettings.JSONLD_MODE, JSONLDMode.COMPACT);
rdfWriter.getWriterConfig().set(JSONLDSettings.OPTIMIZE, true);
Rio.write(model, rdfWriter);
String output = stringWriter.toString();
}
It gives me a JSON-LD string, but without any indentation, spaces or line breaks such that System.out.println(output)
is not human-readable. It looks like this:
{"@context":"http://schema.org/","type":"Person","jobTitle":"Professor","name":"Jane Doe","telephone":"(425) 123-4567","url":"http://www.janedoe.com"}
In Apache Jena there is an RDFFormat
called JSONLD_PRETTY
which would give me the desired output format. It looks similar to this:
{
"@context": "http://schema.org/",
"@graph": [
{
"id": "_:b0",
"type": "Person",
"jobTitle": "Professor",
"name": "Jane Doe",
"telephone": "(425) 123-4567",
"url": "http://www.janedoe.com"
}
]
}
Is this also possible with Eclipse RDF4J?
Thank you in advance!
Edit:
When I am trying to store the JSON-LD string with MongoDB it throws this error: Invalid BSON field name
. Is this an issue with the serialization or with my built model?
Edit No. 2: The above code works flawlessy with the Turtle format, for example. I am having this problem just with JSON-LD and RDFJSON.
This is possible, by setting the BasicWriterSettings.PRETTY_PRINT
option to true
:
rdfWriter.getWriterConfig().set(BasicWriterSettings.PRETTY_PRINT, true);
No idea about the MongoDB issue, sounds like it should be a separate question.