Home > database >  C# Json converting hex literal string to int
C# Json converting hex literal string to int

Time:12-01

A bit stuck, (confusing myself really, I think).

I am wanting to convert a value from a JSON string from it String representation of hex to an int. I only need to get the value I will never need to write the other way.

For instance

{
   "name" : "someName",
   "id" : "b1"
}

I have a class created

public class Person
{
   public string name;
   [JsonConverter(typeof(myConverter))]
   public int id;
}

and my converter (I am not sure I understand this part correctly)

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;
    }    

I will of course add additional checks to validate data and what not, but I wanted to start with something to see how it worked.

So with the above example I would want my int to be 177

Any help, guidance would be appreciated.

CodePudding user response:

Try following Command to Convert a Hex-Number to an int

var hex = "b1"
int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);

CodePudding user response:

Are you using Newtonsoft.Json? I notice your code wouldn't work on .NET System.Text.Json since:

  • There is no public non-generic version of JsonConverter.

  • It wouldn't work on id because it's not a property.

Here's the working code for System.Text.Json:

public class HexConverter : JsonConverter<int>
{

    public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetString();
        return Convert.ToInt32(value, 16);
    }

    public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}

The class has to contain properties to be deserialized:

public class Person
{

    public string name { get; set; }

    [JsonConverter(typeof(HexConverter))]
    public int id { get; set; }

}

Usage:

const string json = @"{
   ""name"" : ""someName"",
   ""id"" : ""b1""
}";

var person = JsonSerializer.Deserialize<Person>(json, new JsonSerializerOptions());

Console.WriteLine(person!.id);
// Result: 177

This case Convert.ToInt32 works for me, but you can also use int.Parse as suggested in the other answer.

  • Related