0

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.

phly
  • 185
  • 1
  • 12

1 Answers1

1

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.

Jeen Broekstra
  • 21,642
  • 4
  • 51
  • 73
  • First of all, thank you! That is the setting I was looking for. But there is a new problem: `JSONLDMode.FLATTEN` as well as `JSONLDMode.EXPAND` does not deliver well-formed JSON. The first character in the string is `[`and not `{`. That is maybe the reason why it is not storable in MongoDB. Furthermore, it does not use the namespaces I have declared, so there is no `@context` object. But if I use `JSONLDMode.COMPACT` everything works just fine. Do you know what could cause this behaviour? – phly Feb 04 '17 at 11:58
  • It looks as if it turns it into an array with one element. This is in fact well-formed JSON, but admittedly it is a bit odd. I'm not immediately sure why this happens - I suggest you log a [support request](https://github.com/eclipse/rdf4j/issues) with the RDF4J project. – Jeen Broekstra Feb 04 '17 at 23:26