【问题标题】:Convert string which contains ascii mixed with text转换包含与文本混合的 ascii 的字符串
【发布时间】:2022-12-05 19:41:47
【问题描述】:

我不得不处理我发送的数据并且无法控制源。我拥有的数据是 json,但在其他 JSON 中作为字符串发送,所以有点乱,例如:

"{\u0022Products\u0022:[{\u0022ProductName\u0022:\u0022Foo Bar\u0022,\u0022SomethingElse\u0022:null},{\u0022ProductName\u0022:\u0022Foo 酒吧 Pro\u0022,\u0022AnotherThing\u0022:null}],\u0022CustomerRequiredDate\u0022:\u00222022-10-27T16:05:58.4528008\u002B01:00\u0022}"

我想将其反序列化为我拥有的用于保存数据的类,清理后的数据应该是:

{“产品”:[{“ProductName”:“Foo Bar”,“SomethingElse”:null},{“ProductName”:“Foo Bar Pro”,“AnotherThing”:null}],“CustomerRequiredDate”:“2022-10 -27T16:05:58.4528008+01:00"}"

我目前的解决方案是找到一个替换 ascii 的方法,但这只能处理我目前知道它可能包含的 ascii,但它可能包含任何内容,因为我不控制源代码。

string cleanString = Order.OrderState.Replace("\u0022", "\"").Replace("\u002B", "+");
OrderState = JsonSerializer.Deserialize<OrderState>(cleanString );

【问题讨论】:

  • 您是否尝试过反序列化它而不改变它?
  • 这回答了你的问题了吗? How to unescape unicode string in C#
  • \u0022 是等同于 " 的 unicode 编码,在反序列化之前不需要解码。

标签: c# ascii


【解决方案1】:

考虑以 UTF-8 格式发送响应。否则,您可以使用属性对 ASCII 编码进行编码/解码

// hello world
var bytesAscii = new byte [] { 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 };
// All strings in .NET Core are stored as 16-bit Unicode characters.
var utf16string = System.Text.Encoding.ASCII.GetString(bytesAscii);

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 2011-02-19
    • 2011-02-21
    • 1970-01-01
    相关资源
    最近更新 更多