سؤال

This is more of a theoretical question, but I am curious what the difference between these two methods of reading a file is and why I would want to choose one over the other.

I am parsing a JSON configuration file (from local disk). Here is one method of doing it:

// Uses JSON.NET Serializer + StreamReader
using(var s = new StreamReader(file))
{
  var jtr = new JsonTextReader(sr);
  var jsonSerializer = new JsonSerializer();
  return jsonSerializer.Deserialize<Configuration>(jtr);
}

...and, the second option...

// Reads the entire file and deserializes.
var json = File.ReadAllText(file);
return JsonConvert.DeserializeObject<JsonVmrConfigurationProvider>(json);

Is one any better than the other? Is there a case where one or the other should be used?

Again, this is more theoretical, but, I realized I don't really know the answer to it, and a search online didn't produce results that satisfied me. I could see the second being bad if the file was large (it isn't) since it's being read into memory in one shot. Any other reasons?

هل كانت مفيدة؟

المحلول

by reading the code you found that deserializaton from a string finally reach:

public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
    {
        ValidationUtils.ArgumentNotNull(value, "value");

        JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);

        // by default DeserializeObject should check for additional content
        if (!jsonSerializer.IsCheckAdditionalContentSet())
            jsonSerializer.CheckAdditionalContent = true;

        using (var reader = new JsonTextReader(new StringReader(value)))
        {
            return jsonSerializer.Deserialize(reader, type);
        }
    }

That is the creation of a JsonTextReader.

So the difference seems to effectively be the handling of huge files.

-- previous comment temper:

JsonTextReader overrides JsonReader.Close() and handles the stream (if CloseInput is true), but not only.

CloseInput should be true by default as the StringReader is not explicitly disposed in previous fragment of code

نصائح أخرى

With File.ReadAllText(), the entire JSON needs to be loaded into memory first before deserializing it. Using a StreamReader, the file is read and deserialized incrementally. So if your file is huge, you might want to use the StreamReader to avoid loading the whole file into memory. If your JSON file is small (most cases), it doesn't really make a difference.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top