From 43a86a5e72acf85478633f8183468b615aa85607 Mon Sep 17 00:00:00 2001 From: Shravan Rajinikanth Date: Sat, 9 Oct 2021 12:00:42 -0700 Subject: [PATCH] Updated ContextJsonConverter to support array contexts --- Source/Common/ContextJsonConverter.cs | 25 ++++++++++++++++++- .../ContextJsonConverterTest.cs | 12 +++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/Source/Common/ContextJsonConverter.cs b/Source/Common/ContextJsonConverter.cs index d18e4cfb..7dfcf423 100644 --- a/Source/Common/ContextJsonConverter.cs +++ b/Source/Common/ContextJsonConverter.cs @@ -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); @@ -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; diff --git a/Tests/Schema.NET.Test/ContextJsonConverterTest.cs b/Tests/Schema.NET.Test/ContextJsonConverterTest.cs index 81b19346..4653841e 100644 --- a/Tests/Schema.NET.Test/ContextJsonConverterTest.cs +++ b/Tests/Schema.NET.Test/ContextJsonConverterTest.cs @@ -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(json); + + Assert.NotNull(thing?.Context); + Assert.Equal("foo", thing?.Context.Name); + Assert.Equal("en", thing?.Context.Language); + } + [Fact] public void WriteJson_StringContext_ContextHasName() {