saulyasar
saulyasar

Reputation: 815

How to convert json to hexadecimal in c#

I have json string as in example below

{"SaleToPOIRequest":{"MessageHeader":{"ProtocolVersion":"2.0","MessageClass":"Service","MessageCategory":"Login","MessageType":"Request","ServiceID":"498","SaleID":"SaleTermA","POIID":"POITerm1"},"LogoutRequest":{}}}

I want to convert json request to hexadecimal. I tried example in this link but i cannot get the exact conversion because of {,:,",} values.

Actually i can get hexadecimal return but when i reconvert to string i got return as below

{"SaleToPOIReque§7B#§²$ÖW76vTVder":{"ProtocolV¦W'6öâ#¢#"ã"Â$ÚessageClass":"Se§'f6R"Â$ÖW76vT:ategory":"Login"¢Â$ÖW76vUGR#¢*Request","Servic¤B#¢#C"Â%6ÆZID":"SaleTermA",¢%ôB#¢%ôFW&Ú1"},"LogoutReque§7B#§·×

that is not usefull for me

Is there any way to convert this?

Upvotes: 0

Views: 2719

Answers (2)

Jimi
Jimi

Reputation: 32278

You should most probably use Encoding.Unicode to convert the string to a byte array: it's quite possible that some characters cannot be represented by ASCII chars.

Encoding.Unicode (UTF-16LE) always uses 2 bytes, so it's predictable: a sequence of 4 chars in the HEX string will always represent an UFT-16 CodePoint.
No matter what characters the input string contains.

Convert string to HEX:

string input = "Yourstring \"Ваша строка\"{あなたのひも},آپ کی تار";;
string hex = string.Concat(Encoding.Unicode.GetBytes(input).Select(b => b.ToString("X2")));

Convert back to string:

var bytes = new List<byte>();
for (int i = 0; i < hex.Length; i += 2) {
    bytes.Add(byte.Parse(hex.Substring(i, 2), NumberStyles.HexNumber));
}
string original = Encoding.Unicode.GetString(bytes.ToArray());

Upvotes: 1

user10608418
user10608418

Reputation:

So basically the problem is not only converting to hex but also converting back.

This is nothing more then combining 2 answers already on SO:

First for converting we use the answer given here: Convert string to hex-string in C#

Then for the converting back you can use this answer: https://stackoverflow.com/a/724905/10608418

For you it would then look something like this:

class Program
{
    static void Main(string[] args)
    {
        var input = "{\"SaleToPOIRequest\":{\"MessageHeader\":{\"ProtocolVersion\":\"2.0\",\"MessageClass\":\"Service\",\"MessageCategory\":\"Login\",\"MessageType\":\"Request\",\"ServiceID\":\"498\",\"SaleID\":\"SaleTermA\",\"POIID\":\"POITerm1\"},\"LogoutRequest\":{}}}";
        
        var hex = string.Join("",
            input.Select(c => String.Format("{0:X2}", Convert.ToInt32(c))));

        var output = Encoding.ASCII.GetString(FromHex(hex));

        Console.WriteLine($"input: {input}");
        Console.WriteLine($"hex: {hex}");
        Console.WriteLine($"output: {output}");

        Console.ReadKey();
    }

    public static byte[] FromHex(string hex)
    {
        byte[] raw = new byte[hex.Length / 2];
        for (int i = 0; i < raw.Length; i++)
        {
            raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
        }
        return raw;
    }
}

See it in action in a fiddle here:

https://dotnetfiddle.net/axUC5n

Hope this helps and good luck with your project

Upvotes: 2

Related Questions