Skip to content

Commit

Permalink
BCL System.Text.Json migration 11/
Browse files Browse the repository at this point in the history
UT regression: WikibaseTests.
  • Loading branch information
CXuesong committed Aug 25, 2024
1 parent da8036d commit ad97807
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 87 deletions.
11 changes: 6 additions & 5 deletions WikiClientLibrary.Wikibase/Claim.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Text.Json.Nodes;
using Newtonsoft.Json.Linq;
using WikiClientLibrary.Wikibase.DataTypes;

Expand Down Expand Up @@ -225,10 +226,10 @@ internal Contracts.Reference ToContract()
public sealed class Snak
{

private static readonly JObject DirtyDataValuePlaceholder = new JObject();
private static readonly JsonObject DirtyDataValuePlaceholder = new();

private object? _DataValue;
private JObject? _RawDataValue;
private JsonObject? _RawDataValue;

/// <summary>
/// Initializes a snak with specified property ID and empty value.
Expand Down Expand Up @@ -261,7 +262,7 @@ public Snak(string propertyId, object dataValue, WikibaseDataType dataType)
/// <param name="rawDataValue">The raw JSON data value of the property.</param>
/// <param name="dataType">The data value type.</param>
/// <exception cref="ArgumentNullException"><paramref name="propertyId"/> or <paramref name="dataType"/> is <c>null</c>.</exception>
public Snak(string propertyId, JObject rawDataValue, WikibaseDataType dataType)
public Snak(string propertyId, JsonObject rawDataValue, WikibaseDataType dataType)
{
PropertyId = propertyId ?? throw new ArgumentNullException(nameof(propertyId));
DataType = dataType ?? throw new ArgumentNullException(nameof(dataType));
Expand Down Expand Up @@ -316,7 +317,7 @@ public Snak(Entity property, object dataValue)

/// <summary>Raw JSON value of <c>datavalue</c> node.</summary>
/// <remarks>For the cases when <see cref="SnakType"/> is not <see cref="SnakType.Value"/>, this property should be <c>null</c>.</remarks>
public JObject? RawDataValue
public JsonObject? RawDataValue
{
get
{
Expand All @@ -329,7 +330,7 @@ public JObject? RawDataValue
}
Debug.Assert(_DataValue != DirtyDataValuePlaceholder);
if (DataType == null) throw new InvalidOperationException("DataType is null.");
var data = new JObject { { "value", DataType.ToJson(_DataValue) }, { "type", DataType.ValueTypeName } };
var data = new JsonObject { { "value", DataType.ToJson(_DataValue) }, { "type", DataType.ValueTypeName } };
_RawDataValue = data;
return data;
}
Expand Down
77 changes: 26 additions & 51 deletions WikiClientLibrary.Wikibase/Contracts/Entity.cs
Original file line number Diff line number Diff line change
@@ -1,136 +1,111 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using WikiClientLibrary.Infrastructures;

namespace WikiClientLibrary.Wikibase.Contracts;

[JsonObject(MemberSerialization.OptIn)]
internal class Entity
[JsonContract]
internal sealed class Entity
{

[JsonExtensionData]
public IDictionary<string, JToken>? ExtensionData { get; set; }
public IDictionary<string, JsonElement>? ExtensionData { get; set; }

[JsonProperty]
public string? Type { get; set; }

[JsonProperty]
public string? DataType { get; set; }

[JsonProperty]
public string? Id { get; set; }

[JsonProperty]
public IDictionary<string, MonolingualText>? Labels { get; set; }

[JsonProperty]
public IDictionary<string, MonolingualText>? Descriptions { get; set; }

[JsonProperty]
public IDictionary<string, ICollection<MonolingualText>>? Aliases { get; set; }

[JsonProperty]
public IDictionary<string, ICollection<Claim>>? Claims { get; set; }

[JsonProperty]
public IDictionary<string, SiteLink>? Sitelinks { get; set; }

}

[JsonObject(MemberSerialization.OptIn)]
internal class MonolingualText
[JsonContract]
internal sealed class MonolingualText
{

[JsonProperty]
public string Language { get; set; } = "";
public required string Language { get; set; }

[JsonProperty]
// This field must exist, even if Remove == true.
// Otherwise, there will be internal_api_error_TypeError
public string Value { get; set; } = "";

[JsonProperty]
public bool Remove { get; set; }

}

[JsonObject(MemberSerialization.OptIn)]
internal class Claim
[JsonContract]
internal sealed class Claim
{

[JsonProperty]
public Snak? MainSnak { get; set; }

[JsonProperty]
public string? Type { get; set; }

[JsonProperty]
public IDictionary<string, ICollection<Snak>>? Qualifiers { get; set; }

[JsonProperty("qualifiers-order")]
[JsonPropertyName("qualifiers-order")]
public IList<string>? QualifiersOrder { get; set; }

[JsonProperty]
public string? Id { get; set; }

[JsonProperty]
public string? Rank { get; set; }

[JsonProperty]
public IList<Reference>? References { get; set; }

[JsonProperty]
public bool Remove { get; set; }

}

[JsonObject(MemberSerialization.OptIn)]
internal class Snak
[JsonContract]
internal sealed class Snak
{

[JsonProperty]
public string? SnakType { get; set; }

[JsonProperty]
public string Property { get; set; } = "";
public required string Property { get; set; }

[JsonProperty]
public string? Hash { get; set; }

[JsonProperty]
public JObject? DataValue { get; set; }
public JsonObject? DataValue { get; set; }

[JsonProperty]
public string? DataType { get; set; }

}

[JsonObject(MemberSerialization.OptIn)]
internal class Reference
[JsonContract]
internal sealed class Reference
{

[JsonProperty]
public string? Hash { get; set; }

[JsonProperty]
public IDictionary<string, ICollection<Snak>>? Snaks { get; set; }

[JsonProperty("snaks-order")]
[JsonPropertyName("snaks-order")]
public IList<string>? SnaksOrder { get; set; }

}

[JsonObject(MemberSerialization.OptIn)]
internal class SiteLink
[JsonContract]
internal sealed class SiteLink
{

[JsonProperty]
public string Site { get; set; } = "";
public required string Site { get; set; }

[JsonProperty]
public string Title { get; set; } = "";
public string? Title { get; set; }

[JsonProperty]
public IList<string>? Badges { get; set; }

[JsonProperty]
public bool Remove { get; set; }

}
55 changes: 31 additions & 24 deletions WikiClientLibrary.Wikibase/DataTypes/WikibaseDataType.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace WikiClientLibrary.Wikibase.DataTypes;

Expand Down Expand Up @@ -40,13 +41,13 @@ public abstract class WikibaseDataType
/// <summary>
/// Converts the JSON to the CLR value.
/// </summary>
public abstract object Parse(JToken expr);
public abstract object Parse(JsonNode expr);


/// <summary>
/// Converts the CLR value to JSON.
/// </summary>
public abstract JToken ToJson(object value);
public abstract JsonNode ToJson(object value);

/// <inheritdoc />
public override string ToString()
Expand All @@ -62,15 +63,15 @@ public override string ToString()
internal sealed class DelegatePropertyType<T> : WikibaseDataType where T : notnull
{

private readonly Func<JToken, T> parseHandler;
private readonly Func<T, JToken> toJsonHandler;
private readonly Func<JsonNode, T> parseHandler;
private readonly Func<T, JsonNode> toJsonHandler;

public DelegatePropertyType(string name, Func<JToken, T> parseHandler, Func<T, JToken> toJsonHandler)
public DelegatePropertyType(string name, Func<JsonNode, T> parseHandler, Func<T, JsonNode> toJsonHandler)
: this(name, name, parseHandler, toJsonHandler)
{
}

public DelegatePropertyType(string name, string valueTypeName, Func<JToken, T> parseHandler, Func<T, JToken> toJsonHandler)
public DelegatePropertyType(string name, string valueTypeName, Func<JsonNode, T> parseHandler, Func<T, JsonNode> toJsonHandler)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
ValueTypeName = valueTypeName ?? throw new ArgumentNullException(nameof(valueTypeName));
Expand All @@ -87,12 +88,12 @@ public DelegatePropertyType(string name, string valueTypeName, Func<JToken, T> p
/// <inheritdoc />
public override Type MappedType => typeof(T);

public override object Parse(JToken expr)
public override object Parse(JsonNode expr)
{
return parseHandler(expr);
}

public override JToken ToJson(object value)
public override JsonNode ToJson(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Expand Down Expand Up @@ -127,18 +128,19 @@ public static MissingPropertyType Get(string name, string? valueTypeName)
public override string ValueTypeName { get; }

/// <inheritdoc />
public override Type MappedType => typeof(JToken);
public override Type MappedType => typeof(JsonNode);

/// <inheritdoc />
public override object Parse(JToken expr)
public override object Parse(JsonNode expr)
{
return expr;
}

/// <inheritdoc />
public override JToken ToJson(object value)
public override JsonNode ToJson(object value)
{
return JToken.FromObject(value);
// This also creates defensive copy.
return JsonSerializer.SerializeToNode(value)!;
}

}
Expand All @@ -157,7 +159,7 @@ public override JToken ToJson(object value)
public static class BuiltInDataTypes
{

private static string EntityIdFromJson(JToken value)
private static string EntityIdFromJson(JsonNode value)
{
var id = (string)value["id"];
if (id != null) return id;
Expand All @@ -172,7 +174,7 @@ private static string EntityIdFromJson(JToken value)
return id;
}

private static JToken EntityIdToJson(string id)
private static JsonNode EntityIdToJson(string id)
{
if (id == null) throw new ArgumentNullException(nameof(id));
id = id.Trim();
Expand All @@ -186,7 +188,7 @@ private static JToken EntityIdToJson(string id)
{
throw new ArgumentException("Invalid entity identifier. Expect numeric id follows.", nameof(id));
}
var value = new JObject();
var value = new JsonObject();
switch (id[0])
{
case 'P':
Expand Down Expand Up @@ -265,7 +267,7 @@ private static JToken EntityIdToJson(string id)
return WbTime.Parse(time, before, after, timeZone, precision, WikibaseUriFactory.Get(calendar));
}, v =>
{
var obj = new JObject
var obj = new JsonObject
{
{ "time", v.ToIso8601UtcString() },
{ "timezone", v.TimeZone },
Expand Down Expand Up @@ -298,7 +300,10 @@ private static JToken EntityIdToJson(string id)
unit == "1" ? WbQuantity.Unity : WikibaseUriFactory.Get(unit));
}, v =>
{
var obj = new JObject { { "amount", v.Amount.ToString(SignedFloatFormat) }, { "unit", v.Unit.ToString() }, };
var obj = new JsonObject
{
{ "amount", v.Amount.ToString(SignedFloatFormat) }, { "unit", v.Unit.ToString() },
};
if (v.HasError)
{
obj.Add("lowerBound", v.LowerBound.ToString(SignedFloatFormat));
Expand All @@ -319,7 +324,7 @@ private static JToken EntityIdToJson(string id)
public static WikibaseDataType MonolingualText { get; }
= new DelegatePropertyType<WbMonolingualText>("monolingualtext",
e => new WbMonolingualText((string)e["language"], (string)e["text"]),
v => new JObject { { "text", v.Text }, { "language", v.Language } });
v => new JsonObject { { "text", v.Text }, { "language", v.Language } });

/// <summary>
/// Literal data field for mathematical expressions, formula, equations and such, expressed in a variant of LaTeX.
Expand Down Expand Up @@ -353,9 +358,12 @@ private static JToken EntityIdToJson(string id)
= new DelegatePropertyType<WbGlobeCoordinate>("globe-coordinate", "globecoordinate",
e => new WbGlobeCoordinate((double)e["latitude"], (double)e["longitude"],
(double)e["precision"], WikibaseUriFactory.Get((string)e["globe"])),
v => new JObject
v => new JsonObject
{
{ "latitude", v.Latitude }, { "longitude", v.Longitude }, { "precision", v.Precision }, { "globe", v.Globe.ToString() },
{ "latitude", v.Latitude },
{ "longitude", v.Longitude },
{ "precision", v.Precision },
{ "globe", v.Globe.ToString() },
});

/// <summary>
Expand All @@ -372,7 +380,7 @@ private static JToken EntityIdToJson(string id)
public static WikibaseDataType TabularData { get; } = new DelegatePropertyType<string>("tabular-data", "string",
e => (string)e, v => v);

private static readonly Dictionary<string, WikibaseDataType> typeDict = new Dictionary<string, WikibaseDataType>();
private static readonly Dictionary<string, WikibaseDataType> typeDict = new();

static BuiltInDataTypes()
{
Expand All @@ -394,8 +402,7 @@ static BuiltInDataTypes()
public static WikibaseDataType? Get(string typeName)
{
if (typeName == null) throw new ArgumentNullException(nameof(typeName));
if (typeDict.TryGetValue(typeName, out var t)) return t;
return null;
return typeDict.GetValueOrDefault(typeName);
}

}
Loading

0 comments on commit ad97807

Please sign in to comment.