Best ways to split a string with matching curly braces

后端 未结 2 1970
说谎
说谎 2020-12-04 00:39

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:



        
相关标签:
2条回答
  • 2020-12-04 01:11

    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

    0 讨论(0)
  • 2020-12-04 01:18

    I found the best way is to convert your string to an array structure:

    string json = "{\"name\": \"John\"}{\"name\": \"Joe\"}";
    
    json = json.Insert(json.Length, "]").Insert(0, "[").Replace("}{", "},{");
    
    // json now is     [{"name": "John"},{"name": "Joe"}] 
    List<Person> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Person>>(json);
    

    Assuming your class name is Person :

    public class Person
    {
        public string Name { set; get; }
    }
    
    0 讨论(0)
提交回复
热议问题