简体   繁体   中英

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.' 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?

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

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

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