SmallFries BigGuys SmallFries BigGuys - 5 days ago 5
C# Question

Write JSON To Console

I am new to

JSON
and tryin to add a
JSON
string then write it to console. Any attempt I make to write the below message and not what I expected


System.Runtime.Serialization.Json.XmlJsonReader


This is how I tried to write, is this the proper way?

private void WriteToConsole ()
{
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Security"": { ""UsernameToken"": { ""Username"": ""belljeantest"", ""Password"": ""r@b!e$"" } }"), new System.Xml.XmlDictionaryReaderQuotas());
Console.WriteLine(jsonReader);
Console.ReadLine();
}

Answer

This will convert it into an XDocument which you then need to read/use accordingly.

private void WriteToConsole ()
{
    var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Security"": { ""UsernameToken"": { ""Username"": ""belljeantest"", ""Password"": ""r@b!e$"" } }"), new System.Xml.XmlDictionaryReaderQuotas());
    var xml = XDocument.Load(jsonReader);
    Console.Write(xml);
    Console.ReadLine();
}

The above will print the whole XML file. You can query this accordingly using LINQ. For more on XDocument: https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110).aspx

Comments