Jsonconvert returns Exception in Xmlnode

Asked

Viewed 86 times

2

I tried to convert Json to Xml so making it easier to read.

And I used the following code...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Xml;
using Newtonsoft.Json;
using System.Net;

namespace PowderToyUpdater
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            WebClient web = new WebClient();
            var value = web.DownloadString("http://powdertoy.co.uk/Browse/Comments.json?ID=1681176&Start=0&Count=20");

            XmlDocument xml = JsonConvert.DeserializeXmlNode(value, "root");
        }
    }
}

But as soon as Webclient downloads the string it returns:

XmlNodeConverter can only convert JSON that begins with an object

Stacktrace:

em Newtonsoft.Json.Converters.XmlNodeConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   em Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   em Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   em Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   em Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonConverter[] converters)
   em Newtonsoft.Json.JsonConvert.DeserializeXmlNode(String value, String deserializeRootElementName, Boolean writeArrayAttribute)
   em PowderToyUpdater.Program.Main() na C:\Users\Nathan Ferreira\Documents\Visual Studio 2010\Projects\PowderToyUpdater\PowderToyUpdater\Program.cs:linha 26
   em System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   em System.Threading.ThreadHelper.ThreadStart()

The json Code is this:

[{"Username":"Sandwichlizard","UserID":"105412","Gravatar":"\/Avatars\/105412_40.png","Text":"front page.","Timestamp":"1424281388","FormattedUsername":"Sandwichlizard"},{"Username":"ndutoit","UserID":"133746","Gravatar":"http:\/\/www.gravatar.com\/avatar\/88ff6ca3f7391896d88ea1f6ac46c3f8?s=40&d=http%3A%2F%2Fpowdertoy.co.uk%2FDesign%2FImages%2FAvatar.png&r=pg","Text":"what is fp?","Timestamp":"1424279967","FormattedUsername":"ndutoit"},{"Username":"Lord_Bowserinator","UserID":"130740","Gravatar":"\/Avatars\/130740_40.png","Text":"fp again","Timestamp":"1417569227","FormattedUsername":"Lord_Bowserinator"},{"Username":"Sandwichlizard","UserID":"105412","Gravatar":"\/Avatars\/105412_40.png","Text":"sure.  I will make a tutorial save.  that will be easier than just talking about it here.  I will leave a link in this save when it is ready.  I will also publish it.","Timestamp":"1417561239","FormattedUsername":"Sandwichlizard"},{"Username":"Anonymous100","UserID":"92366","Gravatar":"\/Avatars\/92366_40.png","Text":"Sandwich would you mind explaining to me the basic of all thesse fancy filt drives? I know that it has something to do with the fact that a color of filt when beamed at dtec with aray changes the filts color that is next to the dtec, but I dont understand how that info is decoded, and how it is written in the first place.","Timestamp":"1417541787","FormattedUsername":"Anonymous100"},{"Username":"tombattraw","UserID":"85950","Gravatar":"http:\/\/www.gravatar.com\/avatar\/a9a4ec31425b097ae496b8f027cdf016?s=40&d=http%3A%2F%2Fpowdertoy.co.uk%2FDesign%2FImages%2FAvatar.png&r=pg","Text":"try recording a pong game","Timestamp":"1417535992","FormattedUsername":"tombattraw"},{"Username":"Sandwichlizard","UserID":"105412","Gravatar":"\/Avatars\/105412_40.png","Text":"@mecha-man.  sure. I have already started.  I am working on a new printer save using this drive and I realized I needed some things and it forced me into a redesign.  I will PM you.","Timestamp":"1417488946","FormattedUsername":"Sandwichlizard"},{"Username":"mecha-man","UserID":"48475","Gravatar":"\/Avatars\/48475_40.png","Text":"@Sandwichlizard: Wanna work together to make it more compact?","Timestamp":"1417482098","FormattedUsername":"mecha-man"},{"Username":"159819","UserID":"78051","Gravatar":"\/Avatars\/78051_40.png","Text":"is it posable to ither make a biger screen or smaler pixels?","Timestamp":"1417478468","FormattedUsername":"159819"},{"Username":"0356459","UserID":"121388","Gravatar":"http:\/\/www.gravatar.com\/avatar\/56261703f558a3503a1ab238fd4f4dac?s=40&d=http%3A%2F%2Fpowdertoy.co.uk%2FDesign%2FImages%2FAvatar.png&r=pg","Text":"sorry man......but hey front page for a long time! :)","Timestamp":"1417412356","FormattedUsername":"0356459"},{"Username":"Sandwichlizard","UserID":"105412","Gravatar":"\/Avatars\/105412_40.png","Text":"If someone would like to make a new video for this setup I would happily update the save with credit to the author of said video","Timestamp":"1417399984","FormattedUsername":"Sandwichlizard"},{"Username":"Sandwichlizard","UserID":"105412","Gravatar":"\/Avatars\/105412_40.png","Text":"the crappy video is just to demo the drive.  video made way better video's than mine for sure.  thank you for your input.","Timestamp":"1417399892","FormattedUsername":"Sandwichlizard"},{"Username":"0356459","UserID":"121388","Gravatar":"http:\/\/www.gravatar.com\/avatar\/56261703f558a3503a1ab238fd4f4dac?s=40&d=http%3A%2F%2Fpowdertoy.co.uk%2FDesign%2FImages%2FAvatar.png&r=pg","Text":"video did it better 2 times before. -1","Timestamp":"1417318433","FormattedUsername":"0356459"},{"Username":"zsdrfty","UserID":"100327","Gravatar":"\/Avatars\/100327_40.png","Text":"Minecraft is more insane because it has analog computers. oog","Timestamp":"1417281395","FormattedUsername":"zsdrfty"},{"Username":"Imperator","UserID":"123921","Gravatar":"\/Avatars\/123921_40.png","Text":"It's so cool that people can actually make a functioning computer within a game.","Timestamp":"1417269917","FormattedUsername":"Imperator"},{"Username":"handicraftsman","UserID":"108835","Gravatar":"\/Avatars\/108835_40.png","Text":"Sandwichlizard, you can use my tablets without credits ) It's for you ) id:1677416","Timestamp":"1417268811","FormattedUsername":"handicraftsman"},{"Username":"Ilog123","UserID":"104909","Gravatar":"\/Avatars\/104909_40.png","Text":"Try Making a Movie maker so you can copy\/paste your film and check em out","Timestamp":"1417251254","FormattedUsername":"Ilog123"},{"Username":"electronic_steve","UserID":"96362","Gravatar":"\/Avatars\/96362_40.png","Text":"id:1683229 108,3... i won!","Timestamp":"1417237206","FormattedUsername":"electronic_steve"},{"Username":"zsdrfty","UserID":"100327","Gravatar":"\/Avatars\/100327_40.png","Text":"16.7k? We're over 1\/10 of the capacity of a single-sided, single-density 5.25\" floppy disk!","Timestamp":"1417229000","FormattedUsername":"zsdrfty"},{"Username":"Fulchrum","UserID":"95857","Gravatar":"\/Avatars\/95857_40.png","Text":"10\/10, owned some noob in planetside 2 on this save.","Timestamp":"1417210797","FormattedUsername":"Fulchrum"}]

1 answer

2


You need to have a root element in your Json to turn it into XML. Look at this example:

string json = @"{
 2  '?xml': {
 3    '@version': '1.0',
 4    '@standalone': 'no'
 5  },
 6  'root': {
 7    'person': [
 8      {
 9        '@id': '1',
10        'name': 'Alan',
11        'url': 'http://www.google.com'
12      },
13      {
14        '@id': '2',
15        'name': 'Louis',
16        'url': 'http://www.yahoo.com'
17      }
18    ]
19  }
20}";
21
22XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
23// <?xml version="1.0" standalone="no"?>
24// <root>
25//   <person id="1">
26//   <name>Alan</name>
27//   <url>http://www.google.com</url>
28//   </person>
29//   <person id="2">
30//   <name>Louis</name>
31//   <url>http://www.yahoo.com</url>
32//   </person>
33// </root>

At this link you will find a complete explanation about the class and method you are using.

UPDATING

Since I don’t know what code you used to run I changed some things in yours to work. Here it writes a complete XML file, it is far from the final code, but it works 100%.

 static void Main(string[] args)
        {
            
          
WebClient web = new WebClient();
var value = web.DownloadString("http://powdertoy.co.uk/Browse/Comments.json?ID=1681176&Start=0&Count=20");

            string json = @"{
   '?xml': {
     '@version': '1.0',
     '@standalone': 'no'
   },
   'root': {
     'minhaclasse':
[
" + value.Replace("'","\'") + @"

]
  }
}";

XmlDocument xml = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

xml.Save(@"c:\caminho\teste.xml");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.