Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

c# - Best ways to split a string with matching curly braces

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

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

Fiddle: https://dotnetfiddle.net/1lTU2v


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...