Skip to content

Switch more over to System.Text.Json #9819

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion build-tools/installers/create-installers.targets
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,6 @@
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)Mono.Options.dll" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)Mono.Options.pdb" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)MULTIDEX_JAR_LICENSE" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)Newtonsoft.Json.dll" />
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wait, is System.Text.Json in the pack?

It would be needed for .NET framework.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No idea. Probably. We need to figure out how to get #9727 and #8746 working so we can test under .NET framework to catch all this stuff.

<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)NuGet.Common.dll" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)NuGet.Configuration.dll" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)NuGet.DependencyResolver.Core.dll" />
Expand Down
31 changes: 15 additions & 16 deletions src/Xamarin.Android.Build.Tasks/Tasks/BuildAppBundle.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System;
using System.Collections.Generic;
using System.IO;
Expand Down Expand Up @@ -88,26 +88,25 @@ public override bool RunTask ()
}
}

var json = JObject.FromObject (new { });
JsonNode json = JsonNode.Parse ("{}")!;
if (!string.IsNullOrEmpty (CustomBuildConfigFile) && File.Exists (CustomBuildConfigFile)) {
using (StreamReader file = File.OpenText (CustomBuildConfigFile))
using (JsonTextReader reader = new JsonTextReader (file)) {
json = (JObject)JToken.ReadFrom(reader);
}
using Stream fs = File.OpenRead (CustomBuildConfigFile);
using JsonDocument doc = JsonDocument.Parse (fs, new JsonDocumentOptions { AllowTrailingCommas = true });
json = doc.RootElement.ToNode ();
}
var jsonAddition = JObject.FromObject (new {
var jsonAddition = new {
compression = new {
uncompressedGlob = uncompressed,
}
});

var mergeSettings = new JsonMergeSettings () {
MergeArrayHandling = MergeArrayHandling.Union,
MergeNullValueHandling = MergeNullValueHandling.Ignore
};
json.Merge (jsonAddition, mergeSettings);
Log.LogDebugMessage ("BundleConfig.json: {0}", json);
File.WriteAllText (temp, json.ToString ());

var jsonAdditionDoc = JsonSerializer.SerializeToNode (jsonAddition);

var mergedJson = json.Merge (jsonAdditionDoc);
var output = mergedJson.ToJsonString (new JsonSerializerOptions { WriteIndented = true });

Log.LogDebugMessage ("BundleConfig.json: {0}", output);
File.WriteAllText (temp, output);

//NOTE: bundletool will not overwrite
if (File.Exists (Output))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
using Microsoft.Android.Build.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using NuGet.ProjectModel;

namespace Xamarin.Android.Tasks;
Expand Down Expand Up @@ -305,7 +306,7 @@ public Project Resolve (Artifact artifact)
}
}

class MicrosoftNuGetPackageFinder
partial class MicrosoftNuGetPackageFinder
{
readonly PackageListFile? package_list;

Expand All @@ -318,7 +319,7 @@ public MicrosoftNuGetPackageFinder (string? file, TaskLoggingHelper log)

try {
var json = File.ReadAllText (file);
package_list = JsonConvert.DeserializeObject<PackageListFile> (json);
package_list = JsonSerializer.Deserialize<PackageListFile> (json, PackageListFileContext.Default.PackageListFile);
} catch (Exception ex) {
log.LogMessage ("There was an error reading 'microsoft-packages.json', Android NuGet suggestions will not be provided: {0}", ex);
}
Expand All @@ -331,18 +332,26 @@ public MicrosoftNuGetPackageFinder (string? file, TaskLoggingHelper log)

public class PackageListFile
{
[JsonProperty ("packages")]
public List<Package>? Packages { get; set; }
}

public class Package
{
[JsonProperty ("javaId")]
public string? JavaId { get; set; }

[JsonProperty ("nugetId")]
public string? NuGetId { get; set; }
}

[JsonSourceGenerationOptions(
AllowTrailingCommas = true,
WriteIndented = true,
PropertyNameCaseInsensitive = true
)]
[JsonSerializable(typeof(PackageListFile))]
[JsonSerializable(typeof(List<Package>))]
[JsonSerializable(typeof(string))]
internal partial class PackageListFileContext : JsonSerializerContext
{
}
}

public class NuGetPackageVersionFinder
Expand Down
87 changes: 87 additions & 0 deletions src/Xamarin.Android.Build.Tasks/Utilities/JsonExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Nodes;

public static class JsonExtensions
{
public static JsonNode Merge (this JsonNode jsonBase, JsonNode jsonMerge)
{
if (jsonBase == null || jsonMerge == null)
return jsonBase;

switch (jsonBase)
{
case JsonObject jsonBaseObj when jsonMerge is JsonObject jsonMergeObj: {
var mergeNodesArray = new KeyValuePair<string, JsonNode?> [jsonMergeObj.Count];
int index = 0;
foreach (var prop in jsonMergeObj) {
mergeNodesArray [index++] = prop;
}
jsonMergeObj.Clear ();

foreach (var prop in mergeNodesArray) {
jsonBaseObj [prop.Key] = jsonBaseObj [prop.Key] switch {
JsonObject jsonBaseChildObj when prop.Value is JsonObject jsonMergeChildObj => jsonBaseChildObj.Merge (jsonMergeChildObj),
JsonArray jsonBaseChildArray when prop.Value is JsonArray jsonMergeChildArray => jsonBaseChildArray.Merge (jsonMergeChildArray),
_ => prop.Value
};
}
break;
}
case JsonArray jsonBaseArray when jsonMerge is JsonArray jsonMergeArray: {
var mergeNodesArray = new JsonNode? [jsonMergeArray.Count];
int index = 0;
foreach (var mergeNode in jsonMergeArray) {
mergeNodesArray [index++] = mergeNode;
}
jsonMergeArray.Clear ();
foreach (var mergeNode in mergeNodesArray) {
jsonBaseArray.Add (mergeNode);
}
break;
}
default:
throw new ArgumentException ($"The JsonNode type [{jsonBase.GetType ().Name}] is incompatible for merging with the target/base " +
$"type [{jsonMerge.GetType ().Name}]; merge requires the types to be the same.");
}
return jsonBase;
}

public static JsonNode? ToNode (this JsonElement element)
{
switch (element.ValueKind) {
case JsonValueKind.Object:
var obj = new JsonObject ();
foreach (JsonProperty prop in element.EnumerateObject()) {
obj [prop.Name] = prop.Value.ToNode ();
}
return obj;

case JsonValueKind.Array:
var arr = new JsonArray();
foreach (JsonElement item in element.EnumerateArray ()) {
arr.Add (item.ToNode ());
}
return arr;

case JsonValueKind.String:
return element.GetString ();

case JsonValueKind.Number:
return element.TryGetInt32 (out int intValue) ? intValue : element.GetDouble ();

case JsonValueKind.True:
return true;

case JsonValueKind.False:
return false;

case JsonValueKind.Null:
return null;

default:
throw new NotSupportedException ($"Unsupported JSON value kind: {element.ValueKind}");
}
}
}
7 changes: 4 additions & 3 deletions src/Xamarin.Android.Build.Tasks/Utilities/MamJsonParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,11 @@ public XElement ToXml ()
GetReplacementMethods ());
}

static JsonObject ReadJson (string path)
static JsonNode ReadJson (string path)
{
using (var f = File.OpenRead (path)) {
return JsonNode.Parse (f)!.AsObject ();
using (var fs = File.OpenRead (path)) {
using JsonDocument doc = JsonDocument.Parse (fs, new JsonDocumentOptions { AllowTrailingCommas = true });
return doc.RootElement.ToNode () ?? JsonNode.Parse ("{}")!;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
<PackageReference Include="Mono.Cecil" Version="$(MonoCecilVersion)" GeneratePathProperty="true" />
<PackageReference Include="Irony" />
<PackageReference Include="NuGet.ProjectModel" Version="6.13.1" />
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonPackageVersion)" />
<PackageReference Include="System.CodeDom" />
<PackageReference Include="System.IO.Hashing" Version="$(SystemIOHashingPackageVersion)" />
<PackageReference Include="System.Reflection.Metadata" Version="8.0.0" />
Expand Down