0

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.

6
  • 4
    Convert.ToInt32 takes a second parameter for the number base, pass 16. Commented Nov 30, 2021 at 14:59
  • 2
    Does this answer your question? Convert integer to hexadecimal and back again Commented Nov 30, 2021 at 15:00
  • Ugh, I knew that. Let me try, While I may have known that at one point, I forgot in this case. Commented Nov 30, 2021 at 15:04
  • 2
    IMHO I would use int.Parse(existingValue, System.Globalization.NumberStyles.HexNumber);. The reason for this is because your hex values don't seem to be prefixed with 0x and your current implementation could fail. On the other hand if they are prefixed, Convert.ToInt32(existingValue, 16); would suffice. Commented Nov 30, 2021 at 15:06
  • 1
    Does this answer your question? C# Hex String into Hex int Commented Nov 30, 2021 at 15:17

2 Answers 2

3

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

var hex = "b1"
int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

I am using Newtonsoft yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.