Sam
Sam

Reputation: 1898

Deserialize JSON string that supposed for object as string

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?

Upvotes: 0

Views: 1564

Answers (2)

Mariano Luis Villa
Mariano Luis Villa

Reputation: 497

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; }
}

Upvotes: 3

Oleh Nechytailo
Oleh Nechytailo

Reputation: 2195

Good solution:

If you want to preserve the json structure, you can change type to JToken. Then Newtonsoft.Json will store raw json there and you will not lose any information on transformations.

Alternative solution:

You can implement custom json converter.

public class ObjectTostringConverter : JsonConverter<string>
{
    public override bool CanRead => true;
    public override bool CanWrite => true;

    public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var data = JToken.ReadFrom(reader);
        return data.ToString();
    }

    public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
    {
        writer.WriteRaw(value);
    }
}

And mark properties to use this converter

[JsonConverter(typeof(ObjectTostringConverter))]
public string Params { get; set; }

Upvotes: 3

Related Questions