本文介绍了用匹配的花括号分割字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在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?

推荐答案

您可以将SupportMultipleContent标志设置为true的JsonTextReader来读取此非标准JSON.假设您有一个如下所示的类Person:

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

这篇关于用匹配的花括号分割字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 07:52