最好的方式与配对的大brances分割字符串 [英] Best ways to split a string with matching curly brances

查看:147
本文介绍了最好的方式与配对的大brances分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#现在的工作,我用JSON.Net解析JSON字符串来得好,C#对象。我的问题的部分原因是,我得到一些字符串是这样的:

I'm working in C# right now and I'm using JSON.Net to parse json strings to well, C# objects. Part of my problem is that I'm getting some strings like this:

{"name": "John"}{"name": "Joe"}

当我尝试用 JsonConvert反序列化。 DeserializeObject<> ,它抛出一个异常

When I try to deserialize with JsonConvert.DeserializeObject<>, it throws an exception.

我不知道什么是分裂这一大字符串分成较小的最佳途径JSON字符串。

I'm wondering what would be the best way to split of this bigger string into smaller json strings.

我在想通过串去和匹配的0级大括号内。这看起来是个好主意?或者是有一些更好的方法来做到这一点?

I was thinking about going through the string and matching curly braces of "level 0". Does this seem like a good idea? Or is there some better method to do this?

推荐答案

您可以使用 JsonTextReader 设置为true的 SupportMultipleContent 标记阅读本非标准JSON。假设你有一个类,看起来像这样:

You can use a JsonTextReader with the SupportMultipleContent flag set to true to read this non-standard JSON. Assuming you have a class Person that looks like this:

class Person
{
    public string Name { get; set; }
}

您可以反序列化这样的JSON对象:

You can deserialize the JSON objects like this:

string json = @"{""name"": ""John""}{""name"": ""Joe""}";

using (StringReader sr = new StringReader(json))
using (JsonTextReader reader = new JsonTextReader(sr))
{
    reader.SupportMultipleContent = true;

    var serializer = new JsonSerializer();
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.StartObject)
        {
            Person p = serializer.Deserialize<Person>(reader);
            Console.WriteLine(p.Name);
        }
    }
}



小提琴:的 https://dotnetfiddle.net/1lTU2v

这篇关于最好的方式与配对的大brances分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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