简体   繁体   中英

Convert base64 string to JSON .NET

I'm new to C# and I have a client request with a value which is base64 encoded. I'm trying to decode the string and make use of the JSON object. Here is the function I call to decode the base64 string.

    public string FromBase64(string data)
    {
        if (string.IsNullOrEmpty(data)) return data;
        var bytes = Convert.FromBase64String(data);
        return UTF8Encoding.UTF8.GetString(bytes);
    }

How can I convert the return value of this function or modify it to JSON so that I can parse its values?

For example, right now for the value of input value data e0tleSA6ICdhYmMnLCBpc0V4aXN0czogJ3RydWUnfQ== , the current output is "{Key: 'abc', isExists: 'true'}" . The output I want is {Key: 'abc', isExists: 'true'}

You have a base-64 string, and you seem to what a deserialized object; so you'll need multiple steps:

  • decode the base-64 to binary
  • interpret the binary as text
  • define an object model that matches the expected data
  • deserialize the text as the object model

For example:

    static void Main()
    {
        var base64 = @"e0tleSA6ICdhYmMnLCBpc0V4aXN0czogJ3RydWUnfQ==";
        var blob = Convert.FromBase64String(base64);
        var json = Encoding.UTF8.GetString(blob);
        // string: "{Key : 'abc', isExists: 'true'}"
 
        var obj = JsonConvert.DeserializeObject<MyPayload>(json);
        Console.WriteLine(obj.Key);
        Console.WriteLine(obj.IsExists);
    }

    class MyPayload
    {
        public bool IsExists { get; set; }
        public string Key { get; set; }
    }

Your code to turn the base64 into string is working properly so now you need to create a class corresponding to your JSON and deserialize the result of the method:

var content = FromBase64(myBase64);
var myObject = JsonSerializer.Deserialize<MyObject>(content);

I hope I understood your question correctly, here is my code example for a generic method that can create a T object by deserializing a base-64 string:

    public static T FromBase64<T>(string data)
    {
        if (string.IsNullOrEmpty(data))
        {
            return default;
        }
        
        var bytes = Convert.FromBase64String(data);
        var parsedString = Encoding.UTF8.GetString(bytes);
        return JsonSerializer.Deserialize<T>(parsedString);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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