【问题标题】:Using Newtonsoft Json how cast an int value to string使用 Newtonsoft Json 如何将 int 值转换为字符串
【发布时间】:2022-01-22 09:04:31
【问题描述】:

我刚刚开始为需要使用 ArangoDB 的项目检查如何使用 json 进行序列化和反序列化。

目前我有一个测试类AnoherTestPerson

public class AnotherTestPerson
    {
        public AnotherTestPerson(int id, string fullname, int age)
        {
            this.Id = id;
            this.Fullname = fullname;
            this.Age = age;
        }

        public int Id { get; set; }
        public string Fullname { get; set; }
        public int Age { get; set; }
    }

现在,我需要将 Id 值转换为字符串,因为当您将数值作为 _key 传递时,ArangoDB 不起作用,所以我猜我必须从 Arango 驱动程序使用的序列化程序中执行此操作,因为在我要处理的项目中,我们将无法访问要存储在数据库中的实体的类。

任何帮助将不胜感激,因为我仍在学习序列化如何与 Json 和 C# 一起工作。

下面是剩下的代码:

public static async Task Main(string[] args)
    {

        string connectionString = "private";

        var arango = new ArangoContext(cs:connectionString, settings:
            new ArangoConfiguration
            {
                Serializer = new ArangoNewtonsoftSerializer(CustomDataContractResolver.Instance)
                //Using custom contract resolver for automatically changing the Id name
                //from the object class to _key in the Json file
            }
        );
        await arango.Document.CreateAsync("TestDB", typeof(AnotherTestPerson).Name, testPerson);
    }

这是自定义合同解析器。我尝试在此处更改属性的类型,但没有成功。

public class CustomDataContractResolver : DefaultContractResolver
{
    public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        if (property.PropertyName.Equals("Id", StringComparison.OrdinalIgnoreCase))
        {
            property.PropertyName = "_key";
            if(property.PropertyType == Type.GetType("System.Int32"))
            {
                property.PropertyType = Type.GetType("System.String");
            }
        }
        return property;
    }
}

编辑

所以检查了 SBFrancies 的评论,我实现了一个基本的 JsonConverter:

public class ToStringJsonConverted : Newtonsoft.Json.JsonConverter
{
    public static readonly ToStringJsonConverted Instance = new ToStringJsonConverted();

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString());
    }
}

并将其链接到自定义 ContractResolver:

public class CustomDataContractResolver : DefaultContractResolver
{
    public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        if (property.PropertyName.Equals("Id", StringComparison.OrdinalIgnoreCase))
        {
            property.PropertyName = "_key";
            if(property.PropertyType == Type.GetType("System.Int32"))
            {
                property.Converter = ToStringJsonConverted.Instance;
            }
        }
        return property;
    }
}

它可以按照我的意愿进行序列化,但是反序列化现在不起作用。我现在将检查如何读取 Json 文件并对其进行解析。

【问题讨论】:

标签: c# json serialization deserialization arangodb


【解决方案1】:

在 cmets 中的 @SBFrancies 参考资料的帮助下,我得到了序列化和反序列化的工作。

合约解析器:

public class CustomDataContractResolver : DefaultContractResolver
{
    public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        if (property.PropertyName.Equals("Id", StringComparison.OrdinalIgnoreCase))
        {
            property.PropertyName = "_key";
            if(property.PropertyType == Type.GetType("System.Int32"))
            {
                property.Converter = ToStringJsonConverted.Instance;
            }
        }
        return property;
    }
}

JsonConverter:

public class ToStringJsonConverted : Newtonsoft.Json.JsonConverter
{
    public static readonly ToStringJsonConverted Instance = new ToStringJsonConverted();

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        return Int32.Parse((string)reader.Value);
    }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2022-07-28
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多