1
votes

I would like to execute an action by passing an object as a parameter. To do that I have serialized that object to a Json string then converted that string into Hex string, passed that Hex string as parameter in the action link.

I have an object like this,

Product prodObject = new Product { Categories = new Category { CategoryName = "Stationary" }, ProductName = "Book", Price = 250 };

Serialized above object to Json string like this,

var jsontString = JsonConvert.SerializeObject(prodObject);

I have converted above Json String into Hex string using below code.

public string ConvertStringtoHex(string encodeMe, System.Text.Encoding encoding)
    {
        Byte[] stringBytes = encoding.GetBytes(encodeMe);
        StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
        foreach (byte b in stringBytes)
        {
            sbBytes.AppendFormat("{0:X2}", b);
        }
        return sbBytes.ToString();
    }

In my action result return like below,

string hexString = ConvertStringtoHex(jsontString, System.Text.Encoding.Unicode);
return JavaScript(string.Format("document.location = '{0}';", Url.Action("Checkout", "PurchaseModule", new { pid= hexString })));

Again I have converted that Hex string to Json string at the ActionResult Post method then I tried to convert Json string to my original object.

string MyString = ConvertHextoString(pid, System.Text.Encoding.Unicode);

Converted Hex string into Json string using below code,

public static string ConvertHextoString(string decodeMe, System.Text.Encoding encoding)
    {
        int numberChars = decodeMe.Length;
        byte[] bytes = new byte[numberChars / 2];
        for (int i = 0; i < numberChars; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(decodeMe.Substring(i, 2), 16);
        }
        return encoding.GetString(bytes);
    }

De serialized string to Json String like below,

var JsonString = JsonConvert.DeserializeObject(MyString);

I am getting error at the below line code,

Product prodObject = (Product)JsonString;

Here I am getting an error like below. Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Product'.

Does anyone know how to solve this issue?

2
Have you tried deserialising into the correct type? var prodObject = JsonConvert.DeserializeObject<Product>(MyString);freedomn-m
Thanks to @freedomn-m `var prodObject = JsonConvert.DeserializeObject<Product>(MyString);' worked for me.sridharnetha

2 Answers

1
votes

Adding comment as answer:

Deserialise directly into the correct type:

var prodObject = JsonConvert.DeserializeObject<Product>(MyString);
1
votes

try this:

Product prodObject = JsonConvert.DeserializeObject<Product>(MyString);