I need to serialize a string of JSON. But inside this string, it contains objects that I want to serialize as a string.
Look at this JSON string
{
"action":"applyPromo",
"params":
[
{
"transacId":"M123238831",
"promotionId":16,
"promotionTypeId":1,
"amount":100,
"transacTime":"2021-03-19T12:00:30.045+10:00"
}
]
}
Since the action can be anything, I need to store the params as a string which will be deserialized elsewhere.
Here is my class:
public class RequestAction
{
public string action { get; set; }
public string params { get; set; }
public RequestAction()
{
action = params = string.Empty;
}
}
When I tried to deserialize the string using JSON (Newtonsoft), I got this error: Unexpected character encountered while parsing value: [. Path 'params', line 1, position 27.'
.
Here is my code to deserialize the JSON String
public static RequestAction Parse(str)
{
return JsonConvert.DeserializeObject<RequestAction>(str);
}
Any idea how to deserialize params
as string?
If I understood correctly, you need the params
property as raw string. One way to achieve this is to use a JToken:
public class RequestAction
{
public string Action { get; set; } = string.Empty;
public JToken Params { get; set; }
}