|
| 1 | +// <copyright file="StringConverter.cs" company="Selenium Committers"> |
| 2 | +// Licensed to the Software Freedom Conservancy (SFC) under one |
| 3 | +// or more contributor license agreements. See the NOTICE file |
| 4 | +// distributed with this work for additional information |
| 5 | +// regarding copyright ownership. The SFC licenses this file |
| 6 | +// to you under the Apache License, Version 2.0 (the |
| 7 | +// "License"); you may not use this file except in compliance |
| 8 | +// with the License. You may obtain a copy of the License at |
| 9 | +// |
| 10 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +// |
| 12 | +// Unless required by applicable law or agreed to in writing, |
| 13 | +// software distributed under the License is distributed on an |
| 14 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | +// KIND, either express or implied. See the License for the |
| 16 | +// specific language governing permissions and limitations |
| 17 | +// under the License. |
| 18 | +// </copyright> |
| 19 | + |
| 20 | +using System; |
| 21 | +using System.Text; |
| 22 | +using System.Text.Json; |
| 23 | +using System.Text.Json.Serialization; |
| 24 | + |
| 25 | +#nullable enable |
| 26 | + |
| 27 | +namespace OpenQA.Selenium.DevTools.Json; |
| 28 | + |
| 29 | +internal sealed class StringConverter : JsonConverter<string> |
| 30 | +{ |
| 31 | + public override bool HandleNull => true; |
| 32 | + |
| 33 | + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 34 | + { |
| 35 | + try |
| 36 | + { |
| 37 | + return reader.GetString(); |
| 38 | + } |
| 39 | + catch (InvalidOperationException) |
| 40 | + { |
| 41 | + // Fallback to read the value as bytes instead of string. |
| 42 | + // System.Text.Json library throws exception when CDP remote end sends non-encoded string as binary data. |
| 43 | + // Using JavaScriptEncoder.UnsafeRelaxedJsonEscaping doesn't help because the string actually is byte[]. |
| 44 | + // https://chromedevtools.github.io/devtools-protocol/tot/Network/#type-Request - here "postData" property |
| 45 | + // is a string, which we cannot deserialize properly. This property is marked as deprecated, and new "postDataEntries" |
| 46 | + // is suggested for using, where most likely it is base64 encoded. |
| 47 | + |
| 48 | + var bytes = reader.ValueSpan; |
| 49 | + var sb = new StringBuilder(bytes.Length); |
| 50 | + foreach (byte b in bytes) |
| 51 | + { |
| 52 | + sb.Append(Convert.ToChar(b)); |
| 53 | + } |
| 54 | + |
| 55 | + return sb.ToString(); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) => |
| 60 | + writer.WriteStringValue(value); |
| 61 | +} |
0 commit comments