简体   繁体   English

如何在 c# 中将 json 转换为十六进制

[英]How to convert json to hexadecimal in c#

I have json string as in example below我有 json 字符串,如下例所示

{"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.我想将 json 请求转换为十六进制。 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?有什么办法可以转换这个吗?

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:这只不过是在 SO 上结合了 2 个答案:

First for converting we use the answer given here: Convert string to hex-string in C#首先,我们使用此处给出的答案进行转换: Convert string to hex-string in C#

Then for the converting back you can use this answer: https://stackoverflow.com/a/724905/10608418然后对于转换回来,你可以使用这个答案: 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 https://dotnetfiddle.net/axUC5n

Hope this helps and good luck with your project希望这对您的项目有所帮助并祝您好运

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将字符串转换为字节数组:某些字符很可能无法用 ASCII 字符表示。

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. Encoding.Unicode ( UTF-16LE ) 始终使用 2 个字节,因此可以预测:HEX 字符串中的 4 个字符序列将始终表示UFT-16代码点。
No matter what characters the input string contains.无论输入字符串包含什么字符。

Convert string to HEX:将字符串转换为 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM