How to deserialize a JSON string to an object in C #?

3

I receive a variable called productos that contains a list of products in JSON format in the following way:

[{"codigo":"Servilleta","cantidad":2},{"codigo":"Papelhig","cantidad":1}]

I need to deserialize it in order to use the products separately within the method.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDocument prueba(string cliente, string productos)
{
    XmlDocument xml = new XmlDocument();
    var stringdata = "<items>";
    stringdata += "<item>";
    stringdata += "<cliente> " + cliente + "</cliente>";
    stringdata += "<producto> " + productos + "</producto>";
    stringdata += "</item>";
    stringdata += "</items>";
    xml.LoadXml(stringdata);

    return xml;
}
    
asked by Zarkito 06.09.2017 в 23:36
source

2 answers

4

Without using intermediate class:

References:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Dynamic;

In your method:

var listProductos = JsonConvert.DeserializeObject<List<ExpandoObject>>(productos);

foreach(dynamic prod in listProductos){
    Console.WriteLine("Código: " + prod.codigo + " - Cantidad: " + prod.cantidad );
}

You will get

Código: Servilleta - Cantidad: 2
Código: Papelhig - Cantidad: 1

DEMO

Using a class:

You create class Producto :

public class Producto{
    public string Codigo { get; set; }
    public int Cantidad { get; set; }
}

In your method:

var productos = "[{\"codigo\":\"Servilleta\",\"cantidad\":2},{\"codigo\":\"Papelhig\",\"cantidad\":1}]";

var listProductos = JsonConvert.DeserializeObject<List<Producto>>(productos);

foreach(Producto prod in listProductos){
    Console.WriteLine("Código: " + prod.Codigo + " - Cantidad: " + prod.Cantidad);
}

You'll get:

Código: Servilleta - Cantidad: 2
Código: Papelhig - Cantidad: 1

DEMO

Using an anonymous list:

You create an anonymous object and list that will serve as a definition to deserialize.

var definicion = new { Codigo = "", Cantidad = 0 };
var listaDefinicion = new[] { definicion };

var productos = "[{\"codigo\":\"Servilleta\",\"cantidad\":2},{\"codigo\":\"Papelhig\",\"cantidad\":1}]";

var listProductos = JsonConvert.DeserializeAnonymousType(productos, listaDefinicion);

foreach(var prod in listProductos){
    Console.WriteLine("Código: " + prod.Codigo + " - Cantidad: " + prod.Cantidad);
}
Código: Servilleta - Cantidad: 2
Código: Papelhig - Cantidad: 1

DEMO

Reference:

answered by 07.09.2017 в 00:52
3

You can use NewtonSoft Json (It is a complement or dll that you need to add to the project to be able to use it)

Here's the example ( league ):

You need the object to which your json is going to be cast

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

Then you use the function: JsonConvert.DeserializeObject

string json = @"{
   'Email': '[email protected]',
   'Active': true,
   'CreatedDate': '2013-01-20T00:00:00Z',
   'Roles': [
     'User',
     'Admin'
  ]
 }";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);

To add NewtonSoft to your project use the nugets:

Answering the question:

  

In the case of the OP, it is an array that needs to be deserialized. How can   do it?

The JSON (received as a string) that uses the OP has the following structure:

[{"codigo":"Servilleta","cantidad":2},{"codigo":"Papelhig","cantidad":1}]
  • You must create the object to cast it. It should be something like this:

     public class Producto
     {
         public string codigo{ get; set; }
         public decimal cantidad{ get; set; }
     }
    
  • At the moment of deserialiarlo it would have to do something thus:

     List<Producto> productos = JsonConvert.DeserializeObject<List<Producto>>(json);
    
  • Attach an example

        
    answered by 07.09.2017 в 00:39