c#如何将JSON转换为字典< uint32,string>,但也使用十六进制表示键

ru9i0ody  于 2023-10-21  发布在  C#
关注(0)|答案(1)|浏览(151)

我试图从一个JSON文件中解析(解析)一些Dictionary<UInt32, string>。如果UInt32被指定为decimal,则可以完美工作。但是,如果我指定十六进制值,将失败:(我需要以两种方式指定我的数字。
我被困在类型转换,任何提示?
提前感谢,
JSON测试

"TEST_DIC": {
    "0": "NONE",
    "40": "Value_40",
    "0x83": "Value_0x83",        <-- this will fail
}

现在在C#中,我的对象很简单
使用System.Text.Json;<--使用标准的Microsoft JSON库,使用System.Text.Json.Serialization;

public class Cfg
{
    [JsonConverter(typeof(HexConverter))]         <-- tried this converter
    public Dictionary<UInt32, string> TEST_DIC{ get; set; }
}

我尝试创建一个像这样的自定义TypeConverter

public class HexConverter : JsonConverter<Dictionary<UInt32, string>>
{
    public override Dictionary<UInt32, string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetString();
        return null;
    }

    public override void Write(Utf8JsonWriter writer, Dictionary<uint, string> value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}
yc0p9oo0

yc0p9oo01#

基于@ ZdenykJelínek的建议,以下是我的实现。欢迎评论/改进。
public class Uncategorized:JsonConverter<字典<UInt 32,string>> {

public override Dictionary<UInt32, string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
    var dic = JsonSerializer.Deserialize<Dictionary<string, string>>(ref reader, options); // read as string/string dic first

    var newDict = new Dictionary<UInt32, string>();
    foreach (var kvp in dic)
    {
        UInt32 k;

        if (kvp.Key.StartsWith("0x"))
            k = UInt32.Parse(kvp.Key.Replace("0x", ""), NumberStyles.HexNumber);
        else
            k = UInt32.Parse(kvp.Key);

        newDict.Add(k, kvp.Value);

    }

    return newDict;
}

public override void Write(Utf8JsonWriter writer, Dictionary<uint, string> value, JsonSerializerOptions options)
{
    throw new NotImplementedException();
}

}
成员应装饰有:

[JsonConverter(typeof(HexKeyDicConverter))]
    public Dictionary<UInt32, string> TEST_DIC { get; set; }

相关问题