i have a large ObservableCollection that I want to get out as Json file.
I used the following code, But I get an error out of memory
string json = JsonConvert.SerializeObject(content, Formatting.Indented);
await File.WriteAllTextAsync("file.json");
How can I save this huge ObservableCollection in a json file?
Instead of serializing to a string, and then writing the string to a stream, stream it directly:
using var stream = File.Create("file.json");
JsonSerializer.Serialize(stream, content, new JsonSerializerOptions
{
WriteIdented = true
});
try to serialize directly to the file.This way Newtosoft https://www.newtonsoft.com/json/help/html/serializewithjsonserializertofile.htm recomends to do it
using (StreamWriter file = File.CreateText(#"c:\file.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, content);
}
Related
I have below stream which I get from this line where req1 is of HttpResponseMessage type and responseMessage is of type Stream. How can I convert this Stream into a json Object. My end goal is to extract values from the specific keys in this json.
var responseMessage = await req1.Content.ReadAsStreamAsync();
Above answer has a class defined. I didnt want to define different class as my model is dynamic. I found this solution , which worked well and got me the desired result
var serializer = new JsonSerializer();
using (var sr = new StreamReader(responseMessage))
using (var jsonTextReader = new JsonTextReader(sr))
{
var jsObj= serializer.Deserialize(jsonTextReader);
}
try it
// read file into a string and deserialize JSON to a type
Movie movie1 = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(#"c:\movie.json"));
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(#"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
Movie movie2 = (Movie)serializer.Deserialize(file, typeof(Movie));
}
I'm using Newtonsoft.Json library and i can't acomplish a rather simple task:
Serialize an array of floats and then deserialize the same file.
My console aplication looks like this:
var x_train = new float[3];
x_train[0] = 0.23f;
x_train[1] = 11.23f;
x_train[2] = 22.22f;
string output = JsonConvert.SerializeObject(x_train);
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(_pathToSerializedObjects + "\\x_train.json"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, output);
}
//The file is serialized correctly, now the problem is this block of code:
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(_pathToSerializedObjects + "\\x_train.json"))
{
JsonSerializer serializer2 = new JsonSerializer();
var dx = (float[])serializer.Deserialize(file, typeof(float[]));
Console.WriteLine(dx[0]);
Console.WriteLine(dx[1]);
Console.WriteLine(dx[2]);
}
The line :
"var dx = (float[])serializer.Deserialize(file, typeof(float[]));"
Throws:
Newtonsoft.Json.JsonSerializationException: 'Error converting value "[0.23,11.23,22.22]" to type 'System.Single[]'. Path '', line 1, position 20.'
I believe that i'm missusing the Newtonsoft.Json library but i can't find examples
of serializing primitives.
Environment:
.net Core 3.1 (Console app)
Newtonsoft.Json 12.0.3
Thanks in advance.
You are serializing twice. output contains serialized array and you are serializing that string to a file. You don't need JSON serializer to write text that already represents JSON value. You can use File.WriteAllText for that.
I need an example of getting a JSON string from a JsonDocument. I can get properties with RootElement.GetProperty("ItemName") and then call .GetString() but can't see a way to just get the root element as a JSON string?
Here an example:
JsonDocument jdoc = JsonDocument.Parse("{\"a\":123}");
using(var stream = new MemoryStream())
{
Utf8JsonWriter writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
jdoc.WriteTo(writer);
writer.Flush();
string json = Encoding.UTF8.GetString(stream.ToArray());
}
For an easier usage you could put it in an extension method like:
public static string ToJsonString(this JsonDocument jdoc)
{
using (var stream = new MemoryStream())
{
Utf8JsonWriter writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
jdoc.WriteTo(writer);
writer.Flush();
return Encoding.UTF8.GetString(stream.ToArray());
}
}
And use it like:
JsonDocument jdoc = JsonDocument.Parse("{\"a\":123}");
string json = jdoc.ToJsonString();
I have use RootElement to get a JsonElement and then call .ToString().
JsonDocument jdoc = JsonDocument.Parse("{\"a\":123}");
string json = jdoc.RootElement.ToString();
For the record there are 2 code snippets in official doco at How to serialize and deserialize (marshal and unmarshal) JSON in .NET
A. Use JsonDocument to write JSON
The following example shows how to write JSON from a JsonDocument:
(surprisingly long code snippet here)
The preceding code:
Reads a JSON file, loads the data into a JsonDocument, and writes formatted (pretty-printed) JSON to a file.
Uses JsonDocumentOptions to specify that comments in the input JSON are allowed but ignored.
When finished, calls Flush on the writer. An alternative is to let the writer autoflush when it's disposed.
B. Use Utf8JsonWriter
The following example shows how to use the Utf8JsonWriter class:
(...)
The snipped can be adjusted to use JsonDocument.Parse:
using var stream = new System.IO.MemoryStream();
using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
var jsonDocument = JsonDocument.Parse(content);
jsonDocument.WriteTo(writer);
}
var formatted = System.Text.Encoding.UTF8.GetString(stream.ToArray());
I am trying to save a file to the local appdata in a UWP app using Json.
The code creates a file in the folder and then writes the data object to it using Json. Here is the code i use:
StorageFile file = await localstorage.CreateFileAsync("filename.json", CreationCollisionOption.ReplaceExisting)
var filestream = await file.OpenStreamForWriteAsync();
var writer = new StreamWriter(filestream);
var jsonwriter = new JsonTextWriter(writer);
var serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.All;
serializer.Serialize(jsonwriter, DataObject);
Immediately this seems to work and the file seems to be saved successfully, however opening the file manually reveals that it is exactly 16KB and stopped in the middle of an object.
I have been unable to find any mention of a size limitation on any of these objects (streams, StorageFile, Json serializer etc.)
Can anyone explain why the serialization stops at 16KB?
Using the using statement as Romasz suggested and thereby disposing the filestream, writer etc. seems to have fixed my issue.
New code:
StorageFile file = await createFile("filename.json");
using (JsonTextWriter jsonwriter =new JsonTextWriter(new StreamWriter(await file.OpenStreamForWriteAsync())))
{
var serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.All;
serializer.Serialize(jsonwriter, DataObject);
}
Thank you for your answer.
I am using DataContractJsonSerializer to serialize my C# class which has a property that stores web url
public class Info
{
string Url{get; set;}
}
Storing to disk using the following code
FileStream stream = new FileStream("e:\\config.json", FileMode.Create);
var serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(stream, obj);
stream.Close();
Add the following url to object
Info.Url = "https://google.com"
and serializing it I get the following json
"Info": { "Url" : "https:\/\/google.com" }
How can I avoid the escape character \
there is no problem the backslash in the json file.
You can visualize you json content through this site. You will see that the backslash doesn't appear in the visualization
http://jsonviewer.stack.hu/
As #dbc mentioned, is part of the DataContractJsonSerializer.