0

Deparei-me com este erro ao tentar dar Load a um ficheiro XML através de três scripts: Um chamado Item, outro ItemCollection e o script para carregar o ficheiro XML.

Item:

using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;

public class Item : MonoBehaviour {


[XmlAttribute("id")]
public string id;

[XmlAttribute("Nome")]
public string Nome;

[XmlAttribute("Preco")]
public float Preco;
}

ItemCollection

using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using UnityEngine;
using System.IO;


[XmlRoot("DataBase")]
public class ItemCollection : MonoBehaviour {
    [XmlArray("Produtos")]
    [XmlArrayItem("Produto")]
    public List<Item> Produtos = new List<Item>();

    public static ItemCollection Load(string path)
    {
        TextAsset _xml_ = Resources.Load <TextAsset>(path);

        XmlSerializer serializer = new XmlSerializer(typeof(ItemCollection));

        StringReader reader = new StringReader(_xml_.text);

        ItemCollection Produtos = serializer.Deserialize(reader) as ItemCollection;

        reader.Close();

        return Produtos;
    }
}

Loader:

using System.Collections;
using System.Collections.Generic;
using System.Xml.Linq;
using UnityEngine;

public class LoadXml : MonoBehaviour {

    public const string path = "Nomes_E_Precos";

    void Start () {
        ItemCollection itemCollection = ItemCollection.Load(path);

        foreach (Item Produto in itemCollection.Produtos)
        {
            Debug.Log(Produto.Nome + Produto.id + Produto.Preco);
        }
    }


}

No entanto, dá-me o erro(na engine) no título:

To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object)

Alguma solução?

0

2 Respostas 2

0

O está ocorrendo é que o XmlSerializer espera uma classe que seja herdada de IEnumerable, ou seja, que armazene e trate coleções de itens. A lista (List), por exemplo, é uma delas, mas a sua classe ItemCollection (quem de fato você está tentando [de]serializar) não é!

O erro indica que a sua classe não tem o método Add, justamente porque ele está na interface IEnumerable.

Uma solução possível é você tentar (de)serializar diretamente a lista Produtos:

public static List<Item> Load(string path)
{
    TextAsset _xml_ = Resources.Load <TextAsset>(path);

    XmlSerializer serializer = new XmlSerializer(typeof(List<Item>));

    StringReader reader = new StringReader(_xml_.text);

    List<Item> Produtos = serializer.Deserialize(reader) as List<Item>;

    reader.Close();

    return Produtos;
}
0

Tenho uma aplicação em asp.net core 2.1, na qual serializo na controller mesmo. Exemplo:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using System.Web.Http.Cors;
using Vendas.Api.Models;
using Vendas.Api.Service;
namespace Vendas.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Produces("application/json")]
    [EnableCors(origins: "http://localhost:56133/api/Produto", headers: "*", methods: "*")]
    public class ProdutoController : Controller
    {
        private readonly ProdutoService _produtoService;
        public ProdutoController(ProdutoService produtoService)
        {
            _produtoService = produtoService;
        }

        [HttpGet]
        public JsonResult Get()
        {
            var produto = _produtoService.FindAll();
            return Json(produto);
        }

        [HttpGet("{id}")]
        public JsonResult Get(int id)
        {
            var produto = _produtoService.FindById(id);
            return Json(produto);
        }

        [HttpPost]
        public ActionResult<Produto> Post(Produto produto)
        {
            _produtoService.InsertAsync(produto);
            return CreatedAtAction(nameof(Get), new { id = produto.id }, produto);
        }

        [HttpDelete("{id}")]
        public ActionResult<Produto> Delete(int id)
        {
            _produtoService.Remove(id);
            return CreatedAtAction(nameof(Get), new { id = id });

        }
        [HttpPut("{id}")]
        public async Task<IActionResult> Put(int id, Produto produto)
        {
            if (id != produto.id)
            {
                return BadRequest();
            }
            try
            {
                await _produtoService.Update(produto);
            }
            catch (DbUpdateConcurrencyException)
            {
                var cs = _produtoService.FindById(id);
            }
            return CreatedAtAction(nameof(Get), new { id = id });
        }
    }
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .