3

I am reading a json file which contains large data and deserializing it into object. I am trying to increase the performance by reading the bytes and deserialize it. But when I searched it says I have to convert it to string to deserialize it. Is there any way to deserialize directly without converting into string.

Below is what I have done.

byte[] bytesArray = File.ReadAllBytes(path);
var bytesAsString = Encoding.ASCII.GetString(bytesArray);
object person = JsonConvert.DeserializeObject<List<PersonList>>(bytesAsString);

I want to remove the second line and go directly to the next step, ie, skip converting to string.

using (StreamReader file = File.OpenText(path))
{
    JsonSerializer jsonSerializer = new JsonSerializer
    {
       NullValueHandling = NullValueHandling.Ignore
    };
    object person = (object)jsonSerializer.Deserialize(file, typeof(List<PersonList>));
}

Above code I read the whole file and convert it into object. My aim of reading bytes is to increase the performance of this code.

1

2 Answers 2

1

No. There is no way to deserialize your whole object without converting it to string.

The reason is simple: The Json Deserializer has to read the while JSON (text) to be able to tokenize it. So the deserialization can happen.

Edit: What you can do is to read specific parts of your (big) text file and deserialize them. This can increase your performance. BUT: you have to use string here again

Edit2: When you say "large data", do you mean much required data or just a huge amount of bytes? Maby your class has many data that are not required (like private fields, lists that are generated dynamically). You can "remove" them from your json using the JsonIgnore attribute.

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

5 Comments

I am able to read the file and deserialize it. I have updated the question. Is there any way to make it more fast.
then replace File.ReadAllBytes(path); with File.ReadAllText(path);
and store it directly in a string variable
and: if you already specify the type of the deserialized object, don't store the result in a Object variable, please use var or List<PersonList>>
I decided to stick to what i have as of now
1

You need the string to deserialize... But maybe you can call System.IO.File.ReadAllText() directly... But i dont think this increases the speed very much because also ReadAllText has to encode.

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.