c# - Json.Net 反序列化字符串中的 JSON 字符串

标签 c# json string json.net

这听起来很简单。但我找不到如何去做。

我从 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/

相关文章:

c# - 使用 XSL-FO 在 .NET 中生成 PDF

ios - JSON + 3des加密无效

android - 已弃用 HttpClient?

ios - Swift 3 和 JSON——通过在后台运行 URL 来更新数据库

Python - 使用前 2 个元素转换列

c# - 将委托(delegate)作为参数的方法?

c# - 使用C#删除硬盘驱动器上的可用空间

c# - 将 GraphQL 查询映射到 Select() linq 到 sql

c# - 如何通过换行字典<string,string>将字符串拆分为键值对

.net - 有没有更好的方法来删除 .NET 中字符串的尾随部分?