Can you deserialize and map a Json without model in C #?

0

What happens is that I have a requirement, I have a Json but I need to capture the value, but I have to do it without using a Model, I have seen examples but they all manage models.

Is it possible to deserialize without a model?

At the moment I'm doing it like this:

Step 1:

I create the Json from PostMan

{
   "CAMPO_EN_LA_TABLA": "valor que quiero capturar"
}

Step 2:

Create a Private model in the class, to be able to serialize:

private class Parametros
{
    [Key]
    public int Empid { get; set; }

    public string Codigo { get; set; }

    [Column(TypeName = "sql_variant")]
    public object Valor { get; set; }
}

Step 3:

I deserialize it in a Dictionary:

var listParametros = JsonConvert.DeserializeObject<Parametros>(valor.ToString());

Step 4:

And the last thing is to capture the value and save it in some parameter:

object ValorCapturado = listParametros.Valor;
Console.WriteLine("Este es el valor impreso: " + listParametros.Valor);

As you can see I know how to deserialize, but in the requirements they ask me to do it without the Model, but I do not know how to map it like this

    
asked by Wilmilcard 30.10.2018 в 16:31
source

3 answers

1

If you need to deserialize generically, you can use JObject

Parsing JSON Object using JObject.Parse

string json = @"{
  CPU: 'Intel',
  Drives: [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}";

JObject o = JObject.Parse(json);

can be deserialized without an object

Using JSON.NET for dynamic JSON parsing

Analyze the title "Importing JSON with JObject.Parse () and JArray.Parse ()" but basically define

var jsonString = @"{""Name"":""Rick"",""Company"":""West Wind"",
                    ""Entered"":""2012-03-16T00:03:33.245-10:00""}";

dynamic json = JValue.Parse(jsonString);

string name = json.Name;
string company = json.Company;
DateTime entered = json.Entered;

when using dynamic you would not have problem in deserializar the json without a class

If you use the JObject you can access the nodes

Parse JSON object in C # with different value types

string sampleJson = "{\"results\":[" +
    "{\"employeename\":\"name1\",\"employeesupervisor\":\"supervisor1\"}," +
    "{\"employeename\":\"name2\",\"employeesupervisor\":\"supervisor1\"}," +
    "{\"employeename\":\"name3\",\"employeesupervisor\":[\"supervisor1\",\"supervisor2\"]}" +
    "]}";

// Parse JSON into dynamic object, convenient!
JObject results = JObject.Parse(sampleJson);

// Process each employee
foreach (var result in results["results"])
{
    // this can be a string or null
    string employeeName = (string)result["employeename"];

  //resto codigo

In summary you could use the JObject or dynamic to deserialize without a class with which to map the json

    
answered by 30.10.2018 / 16:46
source
0

Try doing the following:

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);

We obtain a dynamic object without using a model. I hope it serves you, Regards!

Documentation

    
answered by 30.10.2018 в 16:48
0

One way to do what you're looking for is to use the dynamic and JsonConvert.DeserializeAnonymousType Method (String, T)

using Newtonsoft.Json;
//Creo un string con un JSON de ejemplo
string JsonDeEjemplo = "[{'CAMPO_EN_LA_TABLA': 'valor que quiero capturar'}, {'CAMPO_EN_LA_TABLA': 'segundo valor que quiero capturar'}, {'CAMPO_EN_LA_TABLA': 'tercer valor que quiero capturar'}]";            
//Uso DeserializeAnonymouseType para obtener un List<dynamic> con el contenido deserializado
var ListaDinamica = JsonConvert.DeserializeAnonymousType<List<dynamic>>(JsonDeEjemplo,null);
//Por cada variable dynamic en ListaDinamica..
foreach(var Dyn in ListaDinamica)
{
    //Muestro la propiedad CAMPO_EN_LA_TABLA
    Console.WriteLine(Dyn.CAMPO_EN_LA_TABLA);
}

I leave you a dotnetfiddle of the working example

    
answered by 30.10.2018 в 16:58