如何维护 JSON 值文本中的回车/换行值 (\r\n)?

发布于 2024-12-22 07:25:22 字数 1046 浏览 6 评论 0原文

我是 JSON 新手,我被分配了一个项目,我需要从第三方 Web 服务使用它。我决定使用 Json.NET,因为它看起来相当完整,而且似乎可以解决很多问题。

有很多文本,我在维护回车/换行对时遇到困难。

我可以使用此测试重复问题:

public class MyClass
{
    public string value { get; set; }
}

[Test]
public void HandleNewLines2()
{
    var value = "ALERT \r\n\r\n\r\n.  5010";
    var json = @"{""value"": """ + value + @"""}";
    MyClass myClass = JsonConvert.DeserializeObject<MyClass>(json);
    Assert.IsNotNull(myClass);
    Assert.AreEqual(value, myClass.value);
}

它失败了:

HandleNewLines2 : Failed  Expected string length 19 but was 16. Strings differ at index 7.
  Expected: "ALERT \r\n\r\n\r\n.  5010"
  But was:  "ALERT \r\r\r.  5010"
  --------------------^

换行符 (\n) 在 JsonTextReader::MoveNext 方法中通过以下方式删除

    case CarriageReturnValue:
      if (_reader.Peek() == LineFeedValue)
        _reader.Read();

      _currentLineNumber++;
      _currentLinePosition = 0;
      break;

:维护值中的回车/换行对的方法?

I am new to JSON and I have been assigned a project where I need to consume it from a third-party web service. I decided to use Json.NET because it looks to be pretty complete and it seems to just figure out a lot of stuff.

There is a lot of text and I'm having trouble maintaining the carriage return/line feed pairs.

I can duplicate the problem using this test:

public class MyClass
{
    public string value { get; set; }
}

[Test]
public void HandleNewLines2()
{
    var value = "ALERT \r\n\r\n\r\n.  5010";
    var json = @"{""value"": """ + value + @"""}";
    MyClass myClass = JsonConvert.DeserializeObject<MyClass>(json);
    Assert.IsNotNull(myClass);
    Assert.AreEqual(value, myClass.value);
}

It fails with this:

HandleNewLines2 : Failed  Expected string length 19 but was 16. Strings differ at index 7.
  Expected: "ALERT \r\n\r\n\r\n.  5010"
  But was:  "ALERT \r\r\r.  5010"
  --------------------^

The line feeds (\n) get removed in the JsonTextReader::MoveNext method by the following:

    case CarriageReturnValue:
      if (_reader.Peek() == LineFeedValue)
        _reader.Read();

      _currentLineNumber++;
      _currentLinePosition = 0;
      break;

Is there a way to maintain the carriage return/line feed pairs in the value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文