0

i have a lass like this

    public class Params
    {
        public string FirstName;
        public string SecondName;
        public string Path;
        public long Count;
        public double TotalSize;
        public long Time;
        public bool HasError;

        public Params()
        {

        }
        public Params(string firstName, string secondName, string path, long count, double totalSize, long time, bool hasError)
        {
            FirstName = firstName;
            SecondName = secondName;
            Path = path;
            Count = count;
            TotalSize = totalSize;
            Time = time;
            HasError = hasError;
        }
}

I have the json class like this:

    public static class FileWriterJson
    {
        public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = true) where T : new()
        {
            TextWriter writer = null;
            try
            {
                var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
                writer = new StreamWriter(filePath, append);
                writer.Write(contentsToWriteToFile);

            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }

        public static T ReadFromJsonFile<T>(string filePath) where T : new()
        {

            TextReader reader = null;
            try
            {
                reader = new StreamReader(filePath);
                var fileContents = reader.ReadToEnd();
                return JsonConvert.DeserializeObject<T>(fileContents);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }
}

The main program is like this

 var Params1 = new Params("Test", "TestSecondName", "Mypath",7, 65.0, 0, false);
 FileWriterJson.WriteToJsonFile<Params>("C:\\Users\\myuser\\bin\\Debug\\test1.json", Params1);
 FileWriterJson.WriteToJsonFile<Params>("C:\\Users\\myuser\\bin\\Debug\\test1.json", Params1);

This is mine test1.json:

{"FirstName":"Test","SecondName":"TestSecondName","Path":"Mypath","Count":7,"TotalSize":65.0,"Time":0,"HasError":false}{"FirstName":"Test","SecondName":"TestSecondName","Path":"Mypath","Count":7,"TotalSize":65.0,"Time":0,"HasError":false}

As you can see i have two json objects written in the file.

What i need to do is:

void ReadAllObjects(){
//read the json object from the file
 // count the json objects - suppose there are two objects 
for (int i=0;i<2;i++){ 
//do some processing with the first object 
// if processing is successfull delete the object (i don't know how to delete the particular json object from file) 
 } }

but when i read like this

var abc =FileWriterJson.ReadFromJsonFile<Params>(
                            "C:\\Users\\myuser\\bin\\Debug\\test1.json");

i get the following error:

"Additional text encountered after finished reading JSON content: {. Path '', line 1, position 155."

Then i used the following code to read the JSON file

public static IEnumerable<T> FromDelimitedJson<T>(TextReader reader, JsonSerializerSettings settings = null)
{
    using (var jsonReader = new JsonTextReader(reader) { CloseInput = false, SupportMultipleContent = true })
    {
        var serializer = JsonSerializer.CreateDefault(settings);

        while (jsonReader.Read())
        {
            if (jsonReader.TokenType == JsonToken.Comment)
                continue;
            yield return serializer.Deserialize<T>(jsonReader);
        }
    }
}

}

Which worked fine for me.

Now i need following suggestion:

1> when i put my test1.json data in https://jsonlint.com/ it says Error:

Parse error on line 9:
    ..."HasError": false} { "FirstName": "Tes
    ----------------------^
    Expecting 'EOF', '}', ',', ']', got '{'
    should i write into file in some other way.

2>Is there any better of doing this.

2
  • 2
    You have multiple json in the same file. Without an array structure around them. That's not the standrad, you should try to write a collection with all your item. Commented Apr 20, 2020 at 6:24
  • Or you will need a separator that is impossible in the file. EG if you use new lines, one json per line, you can do something like var result = File.ReadAllLines("path\to\file.txt").Select(line => JsonDeserialize<YourClass>(line)).ToList(); Commented Apr 20, 2020 at 6:26

1 Answer 1

1

You are writing each object out individually to the file. But what you are creating is not a valid JSON file, just a text file with individual JSON objects.

To make it valid JSON, then you need to put the objects into an array or list and then save this to the file.

var Params1 = new Params("Test", "TestFirstName", "Mypath",7, 65.0, 0, false);
var Params2 = new Params("Test 2", "TestSecondName", "Mypath",17, 165.0, 10, false);

List<Params> paramsList = new List<Params>();
paramsList .Add(Params1);
paramsList .Add(Params2);

FileWriterJson.WriteToJsonFile<List<Params>>("C:\\Users\\myuser\\bin\\Debug\\test1.json", paramsList);

FileWriterJson.WriteToJsonFile("C:\Users\myuser\bin\Debug\test1.json", Params1);

Then you should be able to read it in OK. Don't forget to read in a List<Params>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.