Search code examples
c#json-ld

How do I convert json to json-ld in.Net


I am trying to convert json to json-ld. So far I have tried the json-ld.net liberary from nuget (it is part of nuget3): https://www.nuget.org/packages/json-ld.net/

var jtoken = JsonLD.Util.JSONUtils.FromString(response);
var options = new JsonLdOptions();
options.SetBase("http://json-ld.org/test-suite/tests/");
options.SetProduceGeneralizedRdf(true);
var context = JsonLD.Util.JSONUtils.FromString(Properties.Resources.jasonldcontext);
options.SetExpandContext((JObject)context);
var jtokenout = JsonLdProcessor.Compact(jtoken, context, options);
var sz = JSONUtils.ToString(jtokenout);

the context resource:

{"@context": {
"ex": "http://example.org/",
"term1": {"@id": "ex:term1", "@type": "ex:datatype"},
"term2": {"@id": "ex:term2", "@type": "@id"}
}}

My json is present and valid. It comes from REST service. (response), and jtoken is populated. However, sz only contains the context:

context":{"ex":"http://example.org/","term1":
{"@id":"ex:term1","@type":"ex:datatype"},"term2":
{"@id":"ex:term2","@type":"@id"}}}

Solution

  • I think I framed the question incorrectly. POCO to JSON-LD can be accomplished easily with JsonLD.Entities on GitHub. If I start with POCO or convert JSON to POCO, then this works easily.

    var person = new Person
    {
    Id = new Uri("http://t-code.pl/#tomasz"),
    Name = "Tomasz",
    LastName = "Pluskiewicz"
    };
    var @context = JObject.Parse("{ '@context': 'http://example.org/context/Person' }");
    var contextProvider = new StaticContextProvider();
    contextProvider.SetContext(typeof(Person), @context);
    
    // when
    IEntitySerializer serializer = new EntitySerializer(contextProvider);
    dynamic json = serializer.Serialize(person);