Serializing string which has web url to JSon using DataContractJsonSerializer adding backslashes - c#

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.

Related

How to read Json response into Document object of Document AI in C#

I am trying to read json file from cloud storage and trying to convert that into Google.Cloud.DocumentAI.V1.Document.
I have done POC, but its throwing exception Google.Protobuf.InvalidProtocolBufferException: 'Protocol message end-group tag did not match expected tag.'
First I am reading .Json file into MemoryStream and trying to Merge in to Document.
using Google.Cloud.DocumentAI.V1;
public static void StreamToDocument()
{
byte[] fileContents = File.ReadAllBytes("C:\\upload\\temp.json");
using (Stream memoryStream = new MemoryStream(fileContents))
{
Document doc = new Document();
var byteArray = memoryStream;
doc.MergeFrom(byteArray);
}
}
Error Message I am getting is
Is there any other way I can achieve this ?
The code that you've specified there expects the data to be binary protobuf content. For JSON, you want:
string json = File.ReadAllText("C:\\upload\\temp.json");
Document document = Document.Parser.ParseJson(json);

How to Save Large Json Data?

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);
}

Error while deserializing the JSON of float array with Newtonsoft.Json in C# console app

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.

How do I deserialise xml into a DataContract when the XML has had namespaces removed?

I serialise my wcf requests and responses into XML but to save database space, I strip out all non-essential information, so the result is:
<someObject>
<someValue>10</someValue>
</someObject>
There are more complex nested properties, the above is just an example.
When I try to deserialise, I get an error saying expecting someObject, someNamespace but encountered someObject, ''
byte[] data = System.Text.Encoding.UTF8.GetBytes(xmlString);
stream.Write(data, 0, data.Length);
stream.Position = 0;
DataContractSerializer deserializer = new DataContractSerializer(typeof(T));
return deserializer.ReadObject(stream) as T;
Is there an easy way to solve this? Perhaps by not using a DataContractSerializer?
I know this post is almost a week old, but it may help someone if you've already found a solution.
If you know the structure beforehand, you could use the XmlSerializer class.
string xml = "<someObject>" +
" <someValue>10</someValue>" +
"</someObject>";
using (TextReader reader = new StringReader(xml))
{
XmlSerializer serializer = new XmlSerializer(typeof(someObject));
var obj = serializer.Deserialize(reader);
}
Here's the supporting class to deserialize it into:
[Serializable()]
public class someObject
{
[XmlElement("someValue")]
public string someValue { get; set; }
}
For more complex XML, you'd have to modify the class that you're using. You can nest classes as well as support arrays/lists.

Record and replay human-readable protobuf messages using a file with protobuf-csharp-port

I'm using protobuf-csharp-port and I need the ability to record some protobuf messages for replay later. XML would be ideal for me, but I'm flexible as long as a human could go into the file, make changes, then replay the messages from the file.
Using this C# code:
MyRequest req =
MyRequest.CreateBuilder().SetStr("Lafayette").Build();
using (var stringWriter = new StringWriter())
{
var xmlWriterSettings = new XmlWriterSettings
{
ConformanceLevel = ConformanceLevel.Fragment
};
var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings);
ICodedOutputStream output = XmlFormatWriter.CreateInstance(xmlWriter);
req.WriteTo(output);
output.Flush();
string xml = stringWriter.ToString();
using (var streamWriter = new StreamWriter(#"Requests.txt"))
{
streamWriter.WriteLine(xml);
streamWriter.WriteLine(xml);
streamWriter.WriteLine(xml);
}
}
I produce the Requests.txt file containing:
<str>Lafayette</str>
<str>Lafayette</str>
<str>Lafayette</str>
However when I try to deserialize them back using:
var xmlReaderSettings = new XmlReaderSettings
{
ConformanceLevel = ConformanceLevel.Fragment
};
using (var xmlReader = XmlReader.Create(#"Requests.txt", xmlReaderSettings))
{
ICodedInputStream input = XmlFormatReader.CreateInstance(xmlReader);
MyRequest reqFromFile;
while(!input.IsAtEnd)
{
reqFromFile =
ReverseRequest.CreateBuilder().MergeFrom(input).Build();
}
}
Only one MyRequest gets deserialized and the other two are ignored. (After reqFromFile is built, input.IsAtEnd == true.)
So back to my question: is there some way to read multiple human-readable protobuf messages from a file?
So back to my question: is there some way to read multiple human-readable protobuf messages from a file?
Well you're currently creating a single text file with multiple root elements - it's not a valid XML file.
The simplest approach would probably be to create a single XML document with all those requests in, then load it (e.g. with LINQ to XML) and create an XmlReader positioned at each of the root element's children. Each of those XmlReader objects should be able to then deserialize to a single protobuf message.
You could look at the Protocol buffer Editor
Alternatively there is Google own Text format which is a bit like JSon. You can convert between the 2 using the protoc command (look at encode / decode options, you also need the proto definition)

Categories