') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Using `StringValues` with `JsonSerializerContext` produces warnings with `7.0.0-preview*` · Issue #74652 · dotnet/runtime · GitHub
Skip to content

Using StringValues with JsonSerializerContext produces warnings with 7.0.0-preview* #74652

Description

@austindrenski

Description

JsonSerializerContext produces warnings when models contain StringValues due to nullable annotation mismatch.

Reproduction Steps

<ProjectSdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<OutputType>exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReferenceInclude="Microsoft.Extensions.Primitives"Version="7.0.0-preview.7.22375.6" />
<PackageReferenceInclude="System.Text.Json"Version="7.0.0-preview.7.22375.6" />
</ItemGroup>
</Project>
usingSystem;usingSystem.Text.Json.Serialization;usingMicrosoft.Extensions.Primitives;Console.WriteLine("Hello, world!");[JsonSerializable(typeof(SomeClass))][JsonSourceGenerationOptions(GenerationMode=JsonSourceGenerationMode.Default)]publicsealedpartialclassSomeJsonSerializerContext:JsonSerializerContext{}publicsealedclassSomeClass{publicStringValuesSomeStringValues{get;set;}}
$ dotnet buildMSBuild version 17.4.0-preview-22368-02+c8492483a for .NET Determining projects to restore... All projects are up-to-date for restore.C:\Program Files\dotnet\sdk\7.0.100-preview.7.22377.5\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.RuntimeIdentifierInference.targets(219,5): message NETSDK1057: You are using a preview version of .NET. See: https://aka.ms/dotnet-support-policy [C:\Users\adren\rider\system-text-json-source-generator-fails-on-stringvalues\system-text-json-source-generator-fails-on-stringvalues.csproj]C:\Users\adren\rider\system-text-json-source-generator-fails-on-stringvalues\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\SomeJsonSerializerContext.StringValues.g.cs(31,32): warning CS8631: The type 'Microsoft.Extensions.Primitives.StringValues' cannot be used as type parameter 'TCollection' in the generic type or method 'JsonMetadataServices.CreateIListInfo<TCollection, TElement>(JsonSerializerOptions, JsonCollectionInfoValues<TCollection>)'. Nullability of type argument 'Microsoft.Extensions.Primitives.StringValues' doesn't match constraint type 'System.Collections.Generic.IList<string>'. [C:\Users\adren\rider\system-text-json-source-generator-fails-on-stringvalues\system-text-json-source-generator-fails-on-stringvalues.csproj] system-text-json-source-generator-fails-on-stringvalues -> C:\Users\adren\rider\system-text-json-source-generator-fails-on-stringvalues\bin\Debug\net7.0\system-text-json-source-generator-fails-on-stringvalues.dllBuild succeeded.C:\Users\adren\rider\system-text-json-source-generator-fails-on-stringvalues\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\SomeJsonSerializerContext.StringValues.g.cs(31,32): warning CS8631: The type 'Microsoft.Extensions.Primitives.StringValues' cannot be used as type parameter 'TCollection' in the generic type or method 'JsonMetadataServices.CreateIListInfo<TCollection, TElement>(JsonSerializerOptions, JsonCollectionInfoValues<TCollection>)'. Nullability of type argument 'Microsoft.Extensions.Primitives.StringValues' doesn't match constraint type 'System.Collections.Generic.IList<string>'. [C:\Users\adren\rider\system-text-json-source-generator-fails-on-stringvalues\system-text-json-source-generator-fails-on-stringvalues.csproj] 1 Warning(s) 0 Error(s)Time Elapsed 00:00:01.41

Expected behavior

Using StringValues in conjunction with JsonSerializerContext does not produce warnings.

Actual behavior

Using StringValues in conjunction with JsonSerializerContext produces warnings.

warning CS8631: The type 'Microsoft.Extensions.Primitives.StringValues' cannot be used as type parameter 'TCollection' in the generic type or method 'JsonMetadataServices.CreateIListInfo<TCollection, TElement>(JsonSerializerOptions, JsonCollectionInfoValues)'. Nullability of type argument 'Microsoft.Extensions.Primitives.StringValues' doesn't match constraint type 'System.Collections.Generic.IList'.

Regression?

This works when using version 6.0.0 of Microsoft.Extensions.Primitives because the interfaces for StringValues were updated with nullable annotations for 7.0.0-preview*.

Known Workarounds

  • Suppress CS8631
  • Stay on version 6.0.0 of Microsoft.Extensions.Primitives

Configuration

$ dotnet --info.NET SDK: Version: 7.0.100-preview.7.22377.5 Commit: ba310d9309Runtime Environment: OS Name: Windows OS Version: 10.0.22000 OS Platform: Windows RID: win10-x64 Base Path: C:\Program Files\dotnet\sdk\7.0.100-preview.7.22377.5\Host: Version: 7.0.0-preview.7.22375.6 Architecture: x64 Commit: eecb028078

Other information

Not sure where the fix belongs, but here's where the warning bubbles from:

publicstaticJsonTypeInfo<TCollection>CreateIListInfo<TCollection,TElement>(
JsonSerializerOptionsoptions,
JsonCollectionInfoValues<TCollection>collectionInfo)
whereTCollection:IList<TElement>

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additionssource-generatorIndicates an issue with a source generator feature

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions