Skip to content

Commit

Permalink
Updated ContextJsonConverter to support array contexts
Browse files Browse the repository at this point in the history
  • Loading branch information
shravan2x authored and RehanSaeed committed Oct 11, 2021
1 parent 2fb57ff commit 43a86a5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
25 changes: 24 additions & 1 deletion Source/Common/ContextJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public override JsonLdContext ReadJson(JsonReader reader, Type objectType, JsonL
name = (string?)reader.Value;
language = null;
}
else
else if (reader.TokenType == JsonToken.StartObject)
{
var o = JObject.Load(reader);

Expand All @@ -52,6 +52,29 @@ public override JsonLdContext ReadJson(JsonReader reader, Type objectType, JsonL
var languageProperty = o.Property("@language", StringComparison.OrdinalIgnoreCase);
language = languageProperty?.Value?.ToString();
}
else
{
var a = JArray.Load(reader);

name = language = null;
foreach (var entry in a)
{
if (entry.Type == JTokenType.String)
{
name ??= (string?)entry;
}
else
{
var o = (JObject)entry;

var nameProperty = o.Property("name", StringComparison.OrdinalIgnoreCase);
name ??= nameProperty?.Value?.ToString() ?? "https://schema.org";

var languageProperty = o.Property("@language", StringComparison.OrdinalIgnoreCase);
language ??= languageProperty?.Value?.ToString();
}
}
}

#pragma warning disable CA1062 // Validate arguments of public methods
context.Name = name;
Expand Down
12 changes: 12 additions & 0 deletions Tests/Schema.NET.Test/ContextJsonConverterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ public void ReadJson_ObjectContextWithNameAndLanguage_ContextHasNameAndLanguage(
Assert.Equal("en", thing?.Context.Language);
}

[Fact]
public void ReadJson_ArrayContextWithNameAndLanguage_ContextHasNameAndLanguage()
{
var json = "{\"@context\":[\"foo\",{\"@language\":\"en\"}],\"@type\":\"Thing\"}";

var thing = SchemaSerializer.DeserializeObject<Thing>(json);

Assert.NotNull(thing?.Context);
Assert.Equal("foo", thing?.Context.Name);
Assert.Equal("en", thing?.Context.Language);
}

[Fact]
public void WriteJson_StringContext_ContextHasName()
{
Expand Down

0 comments on commit 43a86a5

Please sign in to comment.