Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text file with multiple JSON messages

Tags:

json

c#

.net

I have a text file which contains multiple JSON messages. There is no separator except new line. I have a method which will take JSON string and deserialize it to some object type.

How can I read text file and iterate through each Json string so that it can be deserialized?

Below is the method for deserialize:

public static T JsonDeserialize<T>(string jsonString)
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    T obj = (T)ser.ReadObject(ms);
    return obj;
}
like image 501
Microsoft Developer Avatar asked Sep 17 '25 08:09

Microsoft Developer


1 Answers

You can use jsonReader.SupportMultipleContent Property.
It doesn't matter the separation between the messages newline(s), tab or space(s).

SupportMultipleContent sets a value true/false (default is false) indicating whether multiple pieces of JSON content can be read from a continuous stream without error.

Example:

public static void Main()
{   
    string json = @"
    {
        'Name': 'foo',
        'Id': 123
    }{
        'Name': 'bar',
        'Id': 456
    }
    
    //more new line
    {
        'Name': 'jar',
        'Id': 789
    }
    ";

     var persons = DeserializeObjects<Person>(json).ToList();
     Console.WriteLine(persons.Count());
     foreach ( var person in persons)
    {
      Console.WriteLine("id: {0}, Name: {1}",person.Id, person.Name);
    }

}

    static IEnumerable<T> DeserializeObjects<T>(string input)
    {
        JsonSerializer serializer = new JsonSerializer();
        using (var strreader = new StringReader(input)) 
        using (var jsonreader = new JsonTextReader(strreader))
        {
                //you should use this line
                jsonreader.SupportMultipleContent = true;
                while (jsonreader.Read()) 
                {                       
                    yield return  serializer.Deserialize<T>(jsonreader);
                }
            
        }
    }
     

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

Try it online

output:

3

id: 123, Name: foo

id: 456, Name: bar

id: 789, Name: jar

like image 105
M.Hassan Avatar answered Sep 19 '25 06:09

M.Hassan