【发布时间】:2022-01-07 06:58:00
【问题描述】:
有点卡住了,(我觉得自己真的很困惑)。
我想将 JSON 字符串中的值从十六进制的字符串表示形式转换为 int。我只需要获得我永远不需要以其他方式编写的值。
例如
{
"name" : "someName",
"id" : "b1"
}
我创建了一个类
public class Person
{
public string name;
[JsonConverter(typeof(myConverter))]
public int id;
}
和我的转换器(我不确定我是否正确理解了这部分)
public class myConverter : JsonConverter
{
//CanConvert Boiler Plate
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string sValue = existingValue.ToString().ToUpper();
int iValue = Convert.ToInt32(sValue);
return iValue;
}
我当然会添加额外的检查来验证数据,但我想从一些东西开始,看看它是如何工作的。
所以对于上面的例子,我希望我的 int 是 177
任何帮助,指导将不胜感激。
【问题讨论】:
-
Convert.ToInt32采用第二个参数作为基数,传递 16。 -
呃,我知道。让我试试吧,虽然我可能知道在某一时刻,但在这种情况下我忘记了。
-
恕我直言,我会使用
int.Parse(existingValue, System.Globalization.NumberStyles.HexNumber);。原因是您的十六进制值似乎没有以0x为前缀,并且您当前的实现可能会失败。另一方面,如果它们有前缀,Convert.ToInt32(existingValue, 16);就足够了。 -
这能回答你的问题吗? C# Hex String into Hex int
标签: c# json jsonconvert