none
Deserialize JSON RRS feed

  • Question

  • Hello,

    From a Json Source I'm getting the following information:

    {
    	"Air Elemental":
    	{
    		"layout":"normal",
    		"name":"Air Elemental",
    		"manaCost":"{3}{U}{U}",
    		"cmc":5,
    		"colors":["Blue"],
    		"type":"Creature — Elemental",
    		"types":["Creature"],
    		"subtypes":["Elemental"],
    		"text":"Flying",
    		"power":"4",
    		"toughness":"4",
    		"imageName":
    		"air elemental"
    	},
    
    	"Ancestral Recall":
    	{
    		"layout":"normal",
    		"name":"Ancestral Recall",
    		"manaCost":"{U}",
    		"cmc":1,
    		"colors":["Blue"],
    		"type":"Instant",
    		"types":["Instant"],
    		"text":"Target player draws three cards.",
    		"imageName":"ancestral recall"
    	},
    	
    	"Animate Artifact":
    	{
    		"layout":"normal",
    		"name":"Animate Artifact",
    		"manaCost":"{3}{U}",
    		"cmc":4,
    		"colors":["Blue"],
    		"type":"Enchantment — Aura",
    		"types":["Enchantment"],
    		"subtypes":["Aura"],
    		"text":"Enchant artifact\nAs long as enchanted artifact isn't a creature, it's an artifact creature with power and toughness each equal to its converted mana cost.",
    		"imageName":"animate artifact"
    	},
    }

    I can't seem to succeed to deserialize this. I wrote the following code:

    class Cards { public List<Card> List { get; set; } } class Card { public string layout { get; set; } public string name { get; set; } public string manaCost { get; set; } public int cmc { get; set; } public List<string> colors { get; set; } public string type { get; set; } public List<string> types { get; set; } public List<string> subtypes { get; set; } public string text { get; set; } public string power { get; set; } public string toughness { get; set; } public string imageName { get; set; } }

            public static T GetData<T>(string Api)
            {
                // The data
                object Data;
    
                // Create a request for the URL. 
                WebRequest Request = WebRequest.Create(Api);
    
                // Get the response.
                using (WebResponse Response = Request.GetResponse())
                {
                    // Get the stream containing content returned by the server.
                    using (Stream DataStream = Response.GetResponseStream())
                    {
                        // Open the stream using a StreamReader for easy access.
                        using (StreamReader Reader = new StreamReader(DataStream))
                        {
                            // Read & deserialize the content.
                            Data = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue }.Deserialize<T>(Reader.ReadToEnd());
    
                            // Clean up & dispose the streams and the response.
                            Reader.Close();
                            DataStream.Close();
                            Response.Close();
                            Reader.Dispose();
                            DataStream.Dispose();
                        }
                    }
                }
    
                // Return the data
                return (T)Data;
            }
    Cards CardList = Json.GetData<Cards>(@"<link_to_srouce>");


    Does anyone know what could be wrong?

    Thank you in advance. Best regards, Sam


    Do not fear... Cus we C-sharp here!

    Tuesday, March 17, 2015 9:02 AM

Answers

  • I put your json code into a text file and than read it and it was successful. 

    I tried this code and it is working:

     string filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), @"sample.txt");
                string text = System.IO.File.ReadAllText(filename);
                var json = JsonConvert.DeserializeObject<Dictionary<string, Card>>(text);

    Tuesday, March 17, 2015 5:20 PM
  • All right, if you cannnot change JSON format i advise you to use different json parser ( Json.NET ). Such format:

    {
    	"Air Elemental":
    	{
    		"layout":"normal",
    		"name":"Air Elemental",
    		"manaCost":"{3}{U}{U}",
    		"cmc":5,
    		"colors":["Blue"],
    		"type":"Creature — Elemental",
    		"types":["Creature"],
    		"subtypes":["Elemental"],
    		"text":"Flying",
    		"power":"4",
    		"toughness":"4",
    		"imageName":
    		"air elemental"
    	},
    
    	"Ancestral Recall":
    	{
    		"layout":"normal",
    		"name":"Ancestral Recall",
    		"manaCost":"{U}",
    		"cmc":1,
    		"colors":["Blue"],
    		"type":"Instant",
    		"types":["Instant"],
    		"text":"Target player draws three cards.",
    		"imageName":"ancestral recall"
    	},
    	
    	"Animate Artifact":
    	{
    		"layout":"normal",
    		"name":"Animate Artifact",
    		"manaCost":"{3}{U}",
    		"cmc":4,
    		"colors":["Blue"],
    		"type":"Enchantment — Aura",
    		"types":["Enchantment"],
    		"subtypes":["Aura"],
    		"text":"Enchant artifact\nAs long as enchanted artifact isn't a creature, it's an artifact creature with power and toughness each equal to its converted mana cost.",
    		"imageName":"animate artifact"
    	},
    }

    Can be deserialized to simple dictionary:

        class Card
        {
            public string layout { get; set; }
            public string name { get; set; }
            public string manaCost { get; set; }
            public int cmc { get; set; }
            public List<string> colors { get; set; }
            public string type { get; set; }
            public List<string> types { get; set; }
            public List<string> subtypes { get; set; }
            public string text { get; set; }
            public string power { get; set; }
            public string toughness { get; set; }
            public string imageName { get; set; }
        }

                string jsontxt = File.ReadAllText(@"test.json");
                Dictionary<string, Card> dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Card>>(jsontxt);

    Wednesday, March 18, 2015 9:19 AM

All replies

  • How to: Serialize and Deserialize JSON Data

    https://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx

    chanmm


    chanmm

    Tuesday, March 17, 2015 11:46 AM
  • Hello,

    thank you for your reply, but unfortunatly that doesn't help me at all. I tried alot of things already and that site only shows me default information about the serialization, I know those basics.

    Best regards, Sam


    Do not fear... Cus we C-sharp here!

    Tuesday, March 17, 2015 2:15 PM
  • Do you have any influence on this json format?

    Iam not an expert in json but this file could be hard to parse bacause for each card you are using separate object instead of using list\array. For parsing it you will have to use some third-party tools.

    Instead of that format i would suggest you to use array:

    {"CardList":
    	[
    		{
    		"Key":"Air Elemental",
    		"Value":
    			{
    				"layout":"normal",
    				"name":"Air Elemental",
    				"manaCost":"{3}{U}{U}",
    				"cmc":5,"colors":["Blue"],
    				"type":"Creature — Elemental",
    				"types":["Creature"],
    				"subtypes":["Elemental"],
    				"text":"Flying",
    				"power":"4",
    				"toughness":"4",
    				"imageName":"air elemental"
    			}
    		},
    		{
    		"Key":"Ancestral Recall",
    		"Value":
    			{
    				"layout":"normal",
    				"name":"Ancestral Recall",
    				"manaCost":"{U}",
    				"cmc":1,
    				"colors":["Blue"],
    				"type":"Instant",
    				"types":["Instant"],
    				"subtypes":["a"],
    				"text":"Target player draws three cards.",
    				"power":null,
    				"toughness":null,
    				"imageName":"ancestral recall"
    			}
    		}
    	]
    }

    And for such format the code may look like that:

        [DataContract]
        class Cards
        {
            [DataMember]
            public List<CardElement> CardList { get; set; }
        }
    
        [DataContract]
        class CardElement
        {
            [DataMember]
            public string Key { get; set; }
            [DataMember]
            public Card Value { get; set; }
    
            public CardElement() { }
    
            public CardElement(string key, Card value)
            {
                Key = key;
                Value = value;
            }
        }
    
        [DataContract]
        class Card
        {
            [DataMember]
            public string layout { get; set; }
            [DataMember]
            public string name { get; set; }
            [DataMember]
            public string manaCost { get; set; }
            [DataMember]
            public int cmc { get; set; }
            [DataMember]
            public List<string> colors { get; set; }
            [DataMember]
            public string type { get; set; }
            [DataMember]
            public List<string> types { get; set; }
            [DataMember]
            public List<string> subtypes { get; set; }
            [DataMember]
            public string text { get; set; }
            [DataMember(IsRequired = false)]
            public string power { get; set; }
            [DataMember(IsRequired = false)]
            public string toughness { get; set; }
            [DataMember]
            public string imageName { get; set; }
        }

                string jsontxt = File.ReadAllText(@"test.json");
                Cards c = new JavaScriptSerializer().Deserialize<Cards>(jsontxt);


    • Edited by Mr. Zator Tuesday, March 17, 2015 3:17 PM
    Tuesday, March 17, 2015 3:17 PM
  • Hello Mr. Zator,

    Indeed, I discovered that as well.
    Unfortunatly I have no influence on the Json at all :(

    That's the whole problem, I can't seem to deserialize this.

    Sam


    Do not fear... Cus we C-sharp here!

    Tuesday, March 17, 2015 3:23 PM
  • This is a stupid answer. I did something similar a couple of months ago to deserialize XML. I give Mr. Zator 99% of the answer. I just provided the 1% stupid part of the answer.

                string jsonTxt = File.ReadAllText(@"test.json");
                string modifiedJasonTxt = "{\"CardList\":\n" +
    	           "[\n" +
                   jsonTxt + "\n" +
                   "]\n" +
                   "}\n";
     
                Cards c = new JavaScriptSerializer().Deserialize<Cards>(modifiedJasonTxt);


    jdweng

    Tuesday, March 17, 2015 4:28 PM
  • I put your json code into a text file and than read it and it was successful. 

    I tried this code and it is working:

     string filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), @"sample.txt");
                string text = System.IO.File.ReadAllText(filename);
                var json = JsonConvert.DeserializeObject<Dictionary<string, Card>>(text);

    Tuesday, March 17, 2015 5:20 PM
  • All right, if you cannnot change JSON format i advise you to use different json parser ( Json.NET ). Such format:

    {
    	"Air Elemental":
    	{
    		"layout":"normal",
    		"name":"Air Elemental",
    		"manaCost":"{3}{U}{U}",
    		"cmc":5,
    		"colors":["Blue"],
    		"type":"Creature — Elemental",
    		"types":["Creature"],
    		"subtypes":["Elemental"],
    		"text":"Flying",
    		"power":"4",
    		"toughness":"4",
    		"imageName":
    		"air elemental"
    	},
    
    	"Ancestral Recall":
    	{
    		"layout":"normal",
    		"name":"Ancestral Recall",
    		"manaCost":"{U}",
    		"cmc":1,
    		"colors":["Blue"],
    		"type":"Instant",
    		"types":["Instant"],
    		"text":"Target player draws three cards.",
    		"imageName":"ancestral recall"
    	},
    	
    	"Animate Artifact":
    	{
    		"layout":"normal",
    		"name":"Animate Artifact",
    		"manaCost":"{3}{U}",
    		"cmc":4,
    		"colors":["Blue"],
    		"type":"Enchantment — Aura",
    		"types":["Enchantment"],
    		"subtypes":["Aura"],
    		"text":"Enchant artifact\nAs long as enchanted artifact isn't a creature, it's an artifact creature with power and toughness each equal to its converted mana cost.",
    		"imageName":"animate artifact"
    	},
    }

    Can be deserialized to simple dictionary:

        class Card
        {
            public string layout { get; set; }
            public string name { get; set; }
            public string manaCost { get; set; }
            public int cmc { get; set; }
            public List<string> colors { get; set; }
            public string type { get; set; }
            public List<string> types { get; set; }
            public List<string> subtypes { get; set; }
            public string text { get; set; }
            public string power { get; set; }
            public string toughness { get; set; }
            public string imageName { get; set; }
        }

                string jsontxt = File.ReadAllText(@"test.json");
                Dictionary<string, Card> dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Card>>(jsontxt);

    Wednesday, March 18, 2015 9:19 AM