Deserialize JSON

3

I can POST this information:

{
    "Nritem": 1,
    "Cdprevenda": 3,
    "Cdproduto": 7,
    "Decomplitem": "",
    "Descricao": "Depilação",
    "Dtcadastro": "2015-11-27T13:53:35.120Z",
    "Flsituacao": 1,
    "Md5": "",
    "Qtproduto": 18,
    "Totalizador": "01T1700",
    "Unidade": "UN",
    "Vltabela": 50,
    "Vlunitario": 50,
}

But if you put between [] this message appears:

"itemprevenda":[
  "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'PreVendaWebAPI.Models.Itemprevenda' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath '', line 1, position 1."]

API that does POST:

// POST: api/Itemprevendas
    [ResponseType(typeof(Itemprevenda))]
    public async Task<IHttpActionResult> PostItemprevenda(Itemprevenda itemprevenda)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        //  Implementar o Cditemprevenda e o Nritem automaticamente
        decimal cd = await GetMaiorCod();
        decimal nr = await GetMaiorNr(itemprevenda.Cdprevenda);

        itemprevenda.Cditemprevenda = cd;
        itemprevenda.Nritem = nr;
        //  *******************************************************

        db.Itemprevenda.Add(itemprevenda);

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (ItemprevendaExists(itemprevenda.Cditemprevenda))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = itemprevenda.Cditemprevenda }, itemprevenda);
    }

Pre-order item:

public partial class Itemprevenda
{
    public decimal Cditemprevenda { get; set; }
    public decimal Cdprevenda { get; set; }
    public decimal Cdproduto { get; set; }
    public decimal Nritem { get; set; }
    public decimal Qtproduto { get; set; }
    public decimal Vltabela { get; set; }
    public decimal Vldesconto { get; set; }
    public decimal Vlacrescimo { get; set; }
    public decimal Vlunitario { get; set; }
    public int Flsituacao { get; set; }
    public System.DateTime Dtcadastro { get; set; }
    public string Descricao { get; set; }
    public string Unidade { get; set; }
    public string Totalizador { get; set; }
    public byte[] Md5 { get; set; }
    public string Decomplitem { get; set; }
    public decimal Cdvendedor { get; set; }
    public decimal Vltotal { get; set; }
}

How do I deserialize this JSON?

    
asked by anonymous 29.12.2015 / 12:27

4 answers

0

Correct form:

public async Task<IHttpActionResult> PostItemprevenda(Itemprevenda itemprevenda){}

When Json is between [] the API understands that it is a list of objects, then it has to say that ItemPreview is List this way List<Itemprevenda> . And now just make a foreach and scroll through the list.

    
12.05.2016 / 22:17
3

Use JavaScriptSerializer in the namespace

System.Web.Script.Serialization;

It also has a method called Deserialize where you pass the JSON object and the type in which the JSON will be converted.

Ex:

JavaScriptSerializer serializer = new JavaScriptSerializer();
meuTipo minhaVariavel = serializer.Deserialize(stringJson, meuTipo);
    
29.12.2015 / 12:59
2

Well, I would do a structure like this:

The JSON:

string seujson=
@"{""data"":[{""Cditemprevenda"":""1"",""Cdproduto"":""8""},{""Cditemprevenda"":""2"",""Cdproduto"":""9""}, {""Cditemprevenda"":""3"",""Cdproduto"":""10""}]}";

The classes:

public class Itemprevenda
{

     public List<Item> Items {get;set;}
}

public class Item
{
    public string Cditemprevenda {get;set;}
    public string Cdproduto {get;set;}
}
Itemprevenda item = new JavaScriptSerializer().Deserialize<Itemprevenda>(seujson);

To recover:

foreach(var json in item.Items)
{
   Console.WriteLine("CdItem: {0}, CdProduto: {1}",json.Cditemprevenda ,json.Cdproduto );
}
    
29.12.2015 / 13:04
2

EDITION I had not attended to the fact that deserialization was implied. to receive more than one object of type Itemprevenda you must modify the signature of your method from public async Task<IHttpActionResult> PostItemprevenda(Itemprevenda itemprevenda) to public async Task<IHttpActionResult> PostItemprevenda(Itemprevenda[] itemprevenda) . Note that [] was added after type Itemprevenda .

Making this change your JSON should be sent as follows to your API:

"[{
        "Nritem": 1,
        "Cdprevenda": 3,
        "Cdproduto": 7,
        "Decomplitem": "",
        "Descricao": "Depilação",
        "Dtcadastro": "2015-11-27T13:53:35.120Z",
        "Flsituacao": 1,
        "Md5": "",
        "Qtproduto": 18,
        "Totalizador": "01T1700",
        "Unidade": "UN",
        "Vltabela": 50,
        "Vlunitario": 50,
    }, {
        "Nritem": 2,
        "Cdprevenda": 4,
        "Cdproduto": 8,
        "Decomplitem": "",
        "Descricao": "Depilação 2",
        "Dtcadastro": "2015-11-27T13:53:35.120Z",
        "Flsituacao": 1,
        "Md5": "",
        "Qtproduto": 18,
        "Totalizador": "01T1700",
        "Unidade": "UN",
        "Vltabela": 50,
        "Vlunitario": 50,
    }]";

Your JSON must be sent without a label to the array, otherwise an error will occur in the deserialization of JSON .

Old:

The problem is that if you use without [] it considers only one item and putting [] it considers a vector, array of items.

To do this your model should contain a itemprevenda array with the same attributes as your JSON.

Try to leave your model class similar to this:

///Essa classe será a classe que conterá a sua lista de itens
///de pré venda.
public class Modelo {
    public Itemprevenda[] itemprevenda { get; set; }
}

public partial class Itemprevenda
{
    public decimal Cditemprevenda { get; set; }
    public decimal Cdprevenda { get; set; }
    public decimal Cdproduto { get; set; }
    public decimal Nritem { get; set; }
    public decimal Qtproduto { get; set; }
    public decimal Vltabela { get; set; }
    public decimal Vldesconto { get; set; }
    public decimal Vlacrescimo { get; set; }
    public decimal Vlunitario { get; set; }
    public int Flsituacao { get; set; }
    public System.DateTime Dtcadastro { get; set; }
    public string Descricao { get; set; }
    public string Unidade { get; set; }
    public string Totalizador { get; set; }
    public byte[] Md5 { get; set; }
    public string Decomplitem { get; set; }
    public decimal Cdvendedor { get; set; }
    public decimal Vltotal { get; set; }
}

string seujson = "{
    "itemprevenda": [{
        "Nritem": 1,
        "Cdprevenda": 3,
        "Cdproduto": 7,
        "Decomplitem": "",
        "Descricao": "Depilação",
        "Dtcadastro": "2015-11-27T13:53:35.120Z",
        "Flsituacao": 1,
        "Md5": "",
        "Qtproduto": 18,
        "Totalizador": "01T1700",
        "Unidade": "UN",
        "Vltabela": 50,
        "Vlunitario": 50,
    }]
}";

/*
  Realiza a deserialização do JSON para um objeto do tipo "Modelo"
  que contém o array de Itemprevenda. Modelo com 'M' maiúsculo é a
  classe e com 'm' minúsculo é a variável.
*/
Modelo modelo = new JavaScriptSerializer().Deserialize<Modelo>(seujson);

As you want to receive a string, array , from Itemprevenda objects you must have a class, in this example the Modelo class, to contain this array .

This should solve your problem.

    
29.12.2015 / 13:11