这听起来很简单。但我找不到如何去做。
我从 api 收到了错误的 json。实际的 json 在一个字符串中
代替
[{\"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}]
我收到了
"[{\"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}]"
当我尝试
JsonConvert.DeserializeObject<List<Product>> (jsonString)
我收到错误 Error converting to System.Collections.Generic.List
如何在反序列化之前将其提取为有效的 JSON 字符串?
最佳答案
如果您有一个值是“序列化为 JSON 的字符串”,那么先反序列化它。假设您的字符串真正以双引号开头和结尾,您应该可以调用 JsonConvert.DeserializeObject<string>
做那个展开:
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}");
}
}
关于c# - Json.Net 反序列化字符串中的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44132558/