2

Есть массив объектов класса Vector который нужно сериализовать. Содержимое json файла:

{"length":15,"lineColor":3,"x":0,"y":15}:1,"x":2,"y":5}

Сам класс вектор

  public enum Colors { Red = 1, Blue, Green }

[DataContract]
[Serializable]
public class Vector
{
    [DataMember]
    private int x;
    [DataMember]
    private int y;
    [DataMember]
    private Colors lineColor;
    [DataMember]
    public double length;

    public Vector() { }
    public Vector(int x, int y, Colors lineColor)
    {
        this.x = x;
        this.y = y;
        this.lineColor = lineColor;
        length = Length;
    }

    public double Length
    {
        get { return Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2)); }
        set { length = value; }
    }

    public void AddLength(double a)
    {
        length = Length + a;
    }

    public void Info()
    {
        Console.WriteLine("Line color: {0}\nCoordinates: ({1};{2})\nLength: {3}\n", lineColor, x, y, length);
    }


}

Класс, содержащий методы для сериализаций

    public class Manipulation
{
    public Manipulation() { }

    DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Vector));
    BinaryFormatter bf = new BinaryFormatter();

    public void JSonSerialize(Vector obj)
    {
        using (FileStream fs = new FileStream("serialization.json", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            js.WriteObject(fs, obj);
        }
        Console.WriteLine(" Json serialization completed");
    }

    public void BinarySerialize(Vector obj)
    {
        using(FileStream fs = new FileStream("sr.bin", FileMode.OpenOrCreate))
        {
            bf.Serialize(fs, obj);
        }
        Console.WriteLine("Binary serialization completed");
    }
}

Сериализация в блоке main

class Program
{
    static void Main(string[] args)
    {
        Vector v1 = new Vector(2, 5, (Colors)1);
        Vector v2 = new Vector(-3, 4, (Colors)2);
        Vector v3 = new Vector(0, 15, (Colors)3);

        Manipulation mn = new Manipulation();
        Vector[] vectors = new Vector[3] { v1, v2, v3 };
        foreach(Vector obj in vectors)
        {
            mn.JSonSerialize(obj);
        }
        Console.ReadKey();
    }
}

}

Подобная проблема возникает и при XMl, и при binary сериализации. Буду благодарен за любые советы.

0

1 ответ 1

0
fs.Position = fs.Length;
js.WriteObject(fs, obj);

Но хорошего JSON-a так все равно не получится, так как отдельные объекты надо разделять запятыми, а весь набор - заворачивать в квадратные скобки. Сериализуйте сразу весь массив.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.