Json.Net deserialize JSON string inside a string

This sound very simple. But I can't find how to do it.

I've receiving a bad json from an api. the actual json is inside a string

Instead of

[{\"ProductId\":1,\"ProductName\":\"abuka\",\"Rate\":6.00,\"Quantity\":10.000},{\"ProductId\":2,\"ProductName\":\"abuka\",\"Rate\":6.00,\"Quantity\":10.000},{\"ProductId\":3,\"ProductName\":\"abuka\",\"Rate\":6.00,\"Quantity\":10.000}]

I'm receiving

"[{\"ProductId\":1,\"ProductName\":\"abuka\",\"Rate\":6.00,\"Quantity\":10.000},{\"ProductId\":2,\"ProductName\":\"abuka\",\"Rate\":6.00,\"Quantity\":10.000},{\"ProductId\":3,\"ProductName\":\"abuka\",\"Rate\":6.00,\"Quantity\":10.000}]"

When I try

JsonConvert.DeserializeObject<List<Product>> (jsonString)

I get error Error converting to System.Collections.Generic.List

How can I extract it into a valid JSON string before deserialising?

Jon Skeet
people
quotationmark

If you've got a value which is "a string serialized as JSON", then just deserialize that first. Assuming your string genuinely starts and ends with a double quote, you should be fine to call JsonConvert.DeserializeObject<string> to do that unwrapping:

using System;
using System.IO;
using Newtonsoft.Json;

public class Model
{
    public string Foo { get; set; }
}

public class Test
{
    static void Main()
    {
        string json = "\"{\\\"foo\\\": \\\"bar\\\"}\"";
        Console.WriteLine($"Original JSON: {json}");        
        string unwrappedJson = JsonConvert.DeserializeObject<string>(json);
        Console.WriteLine($"Unwrapped JSON: {unwrappedJson}");
        Model model = JsonConvert.DeserializeObject<Model>(unwrappedJson);
        Console.WriteLine($"model.Foo: {model.Foo}");
    }
}

people

See more on this question at Stackoverflow