【问题标题】:Json.NET boolean JToken cannot deserialize its own serializationJson.NET boolean JToken 无法反序列化自己的序列化
【发布时间】:2019-04-08 20:08:07
【问题描述】:

当序列化一个仅具有布尔值的 JToken 时,第一个字母大写。由于那个大写字母,反序列化结果字符串失败。

以下测试因异常而失败:“解析值时遇到意外字符:T. Path '', line 0, position 0。”

using System;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using Xunit;

public class SimpleTests
{
    [Fact]
    public void TestJTokenBoolean()
    {
        var token = JToken.Parse("true");
        token.Type.Should().Be(JTokenType.Boolean);

        Action deserialize = () => JToken.Parse(token.ToString());
        deserialize.Should().NotThrow();
    }
}

做错了什么?或者可能是一个错误?

【问题讨论】:

标签: c# json.net


【解决方案1】:

我找到了答案。我以错误的方式序列化。此测试有效:

[Fact]
public void TestJTokenBoolean2()
{
    var token = JToken.Parse("true");
    token.Type.Should().Be(JTokenType.Boolean);

    JToken token2 = null;
    using (var stringWriter = new StringWriter())
    {
        token.WriteTo(new JsonTextWriter(stringWriter));
        Action deserialize = () => token2 = JToken.Parse(stringWriter.ToString());
        deserialize.Should().NotThrow();

        token2.Type.Should().Be(JTokenType.Boolean);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    相关资源
    最近更新 更多