JimmyTheOne
JimmyTheOne

Reputation: 233

Deserializing XNA Color from JSON file

I have been building corporate software with VB.NET for a few years now, but have only recently begun creating a game using XNA in VS2010 Express and have been struggling with the transition to C#.

I have the following entity:

public class MyEntity
{
    public String Name { get; set; }
    public Microsoft.Xna.Framework.Color Colour { get; set; }

    public MyEntity(string name, Microsoft.Xna.Framework.Color colour)
    {
        this.Name = name;
        this.Colour = colour;
    }
}

I am planning to store the data for this class in a JSON file, e.g.:

{
    "MyEntities": [
        {"Name": "Entity1", "Colour": {"163", "79", "79"}},
        {"Name": "Entity2", "Colour": {"147", "67", "67"}}
    ]
}

I am aware that the JSON above is incorrect, but I cannot figure out how to correctly store the RGB values for the colours.

In addition, I am struggling to find any examples that demonstrate how to use Newtonsoft.Json to deserialize this JSON file. My latest attempt plainly does not work:

public static List<MyEntity> LoadMyEntities()
{
    List<MyEntity> entities = new List<MyEntity>();
    using (StreamReader file = File.OpenText(@"entities.json"))
    {
        System.Data.DataSet ds = JsonConvert.DeserializeObject<System.Data.DataSet>(file.ReadToEnd());
        System.Data.DataTable dt = ds.Tables["Entities"];
        foreach (System.Data.DataRow row in dt.Rows)
        {
            entities.Add(new MyEntity(row["Name"].ToString(), new Microsoft.Xna.Framework.Color(row["Colour"]));
        }
    }
    return entities;
}

Any assistance would be greatly appreciated as I am utterly stuck at this point.

Upvotes: 0

Views: 1288

Answers (2)

Dan Bechard
Dan Bechard

Reputation: 5291

To do this without any 3rd-party libs:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace test
{
    public struct Color
    {
        public byte R { get; set; }
        public byte G { get; set; }
        public byte B { get; set; }
    }

    [DataContract]
    public class MyEntity
    {
        [DataMember]
        public String Name { get; set; }
        [DataMember]
        public Color Colour { get; set; }

        public MyEntity(string name, Color colour)
        {
            this.Name = name;
            this.Colour = colour;
        }
    }

    class Program
    {
        static DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyEntity));
        static MyEntity entitySave, entityLoad;

        static void Main(string[] args)
        {
            entitySave = new MyEntity("Entity1", new Color() { R = 50, G = 20, B = 50 });
            Serialize(entitySave, "savefile.json");
            bool success = Deserialize(ref entityLoad, "savefile.json");

            if (success && entityLoad.Name == entitySave.Name)
                Console.WriteLine("It works!");
            else
                Console.WriteLine("Uh-oh :(");

            Console.ReadLine();
        }

        static void Serialize(MyEntity entity, string fileName)
        {
            FileStream stream = new FileStream(fileName, FileMode.Create);
            serializer.WriteObject(stream, entity);
            stream.Close();
        }

        static bool Deserialize(ref MyEntity entity, string fileName)
        {
            if (!File.Exists(fileName)) return false;

            FileStream stream = new FileStream(fileName, FileMode.Open);
            entity = (MyEntity)serializer.ReadObject(stream);
            stream.Close();
            return true;
        }
    }
}

This results in a JSON file containing:

{"Colour":{"B":50,"G":20,"R":50},"Name":"Entity1"}

It should work fine with Microsoft.XNA.Framework.Color and List<MyEntity>.

Upvotes: 0

Damith
Damith

Reputation: 63065

change classes as below

public class MyEntity
{
    public string Name { get; set; }
    public Microsoft.Xna.Framework.Color Colour { get; set; }
}

public class RootObject
{
    public List<MyEntity> MyEntities { get; set; }
}

JSON

{
    "MyEntities": [
        {
            "Name": "Entity1",
            "Colour": "23, 33, 33"
        },
        {
            "Name": "Entity2",
            "Colour": "55, 5, 55"
        }
    ]
}

You can Deserialize as below

var result = JsonConvert.DeserializeObject<RootObject>(myjsondata);

Upvotes: 1

Related Questions