Json.Net将字符串内的JSON字符串反序列化 [英] Json.Net deserialize JSON string inside a string

查看:47
本文介绍了Json.Net将字符串内的JSON字符串反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

听起来很简单.但是我找不到方法.

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

我从api接收到错误的json.实际的json在字符串内

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

代替

[{\"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字符串中?

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

推荐答案

如果您有一个序列化为JSON的字符串"的值,则只需将其反序列化即可.假设您的字符串真正以双引号开头和结尾,则可以调用JsonConvert.DeserializeObject<string>进行解包:

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

这篇关于Json.Net将字符串内的JSON字符串反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆