Separate a json string, saving in variables with their respective value

1

This is the result of consulting a webservice

{"Nombre":"Juan","Apellido":"Luna","Edad":26,"FechaNacimiento":"09/03/1990 12:00:00 AM"}

I need some way to separate the values and save them with the name of the variable and the value that corresponds to it, I am doing it in c # I have managed to separate the elements, but I have not been able to create variables and assign values, it should be mentioned that At some point what the json brings may change, they may be more or less values of that I do not have control, so I want to separate them dynamically and assign them in the same way.

EsValido = "{\"Nombre\":\"Juan\",\"Apellido\":\"Luna\",\"Edad\":26,\"FechaNacimiento\":\"09/03/1990 12:00:00 AM\"}";
EsValido = EsValido.Replace(":", "");

String value = EsValido.Trim();

if (value.IndexOf("JUAN") != -1)
{
    string[] delimiter = { ",", "{", "}", "\"" };
    string[] substrings = value.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);

    for (int i = 0; i < substrings.Length; i++)
    {
        if (i % 2 == 0)
        {
            Response.Write(substrings[i] + "<br/>");
        }
    }
}
    
asked by Francisco Guillermo Herrera Ga 08.03.2017 в 19:45
source

3 answers

1

Hello! it's simple the first thing you should do is convert your string to your notation in Objects and do it this way:

public class RootObject
{
    public string Nombre { get; set; }
    public string Apellido { get; set; }
    public int Edad { get; set; }
    public string FechaNacimiento { get; set; }
}

Now, having the object, you only have to convert your JSON String into this object, right? for that magic there are 2 ways, using the native converter of c # and the library Newtonsoft I leave you the 2 solutions:

Using NewtonSoft :

string tuString = "{\"Nombre\":\"Juan\",\"Apellido\":\"Luna\",\"Edad\":26,\"FechaNacimiento\":\"09/03/1990 12:00:00 AM\"}";
RootObject m = JsonConvert.DeserializeObject<RootObject>(tuString);

string name = m.Nombre;
Console.WriteLine(name);

Now with the native C #:

using System.Collections.Generic;
using System.Web.Script.Serialization;

RootObject data = new JavaScriptSerializer().Deserialize<RootObject>(tuString);

Greetings!

    
answered by 08.03.2017 в 20:15
0

As I understand it, what you want to do (in C #) is to receive a JSON and save it in a type object

class Persona{
    string Nombre = "Juan";
    string Apellido = "Luna";
    int Edad = 26;
    DateTime FechaNacimiento = "09/03/1990";
}

If that is the case, do not break your head; there is the library Json de Newtonsoft that processes the Json for you, you just have to go to your documentation to experiment and see what the solution is.

From the outset I tell you that you need to have an object like the one above but with get and set :

public class Persona{
    public string Nombre { get; set; }
    public string Apellido { get; set; }
    public int Edad { get; set; }
    public DateTime FechaNacimiento { get; set; }
}

and then treat your Json with JObject :

var personaIntermedioObject = JObject.Parse(el_json);

to finally assign the data% Persona :

Persona persona = new Persona(){
    Nombre = personaIntermedioObject["Nombre"].ToString(),
    Apellido = personaIntermedioObject["Apellido"].ToString(),
    Edad = Convert.ToInt32(personaIntermedioObject["Edad"]),
    FechaNacimiento = (DateTime)personaIntermedioObject["FechaNacimiento"]
}

Or try to pair it directly with

Persona persona = JsonConvert.DeserializeObject<Persona>(el_json);

EDIT: I think I understand your question. What you will receive is a JSON that can be any structure, not just the one you gave example, style

{nombre:"Juan",edad:"24"}
{estado:"Guanajuato",ciudad:"Celaya"}

and show them (or use them) as

Propiedad | Valor       Propiedad | Valor
---------------------   -----------------------
   nombre | Juan           estado | Guanajuato
     edad | 24             ciudad | Celaya

In that case, following with Json de Newtonsoft, you need a cycle that runs through each of the pairs of Key: Value of the Json. An example that stores the data in a dictionary is:

System.Collections.Generic.Dictionary<string, object> dic = new System.Collections.Generic.Dictionary<string, object>();
foreach(JProperty obj in personaIntermedioObject.Properties())
{
    dic.Add(obj.Name, obj.Value);
    // O bien, imprimirlos en consola:
    Console.WriteLine("Clave: {0} | Valor: {1}", obj.Name, obj.Value.ToString())
}

That way, you can store the information that is, whatever its size, in a structure that you can use later.

My reference: link

EDIT 2:

As far as I know, you can not create variables "on the fly", the closest thing you can do is use an object dynamic as follows:

dynamic DynObj = JObject.Parse(el_json);

That way, you can consult about DynObj.Nombre.ToString() or DynObj.estado.ToString() . Also, why do you want to create these data as variables if you can freely browse all the data with a dictionary? Take into account that even with web pages (what I guess you do for your Response ), before serving the aspx or the cshtml this has to be compiled, you can not be adding the variables as well.

Read about the topic: link

link

link

link

    
answered by 08.03.2017 в 20:05
0

Considering how dynamic the data uses a Dictionary.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var json = "{'Nombre':'Juan','Apellido':'Luna','Edad':26,'FechaNacimiento':'09/03/1990 12:00:00 AM'}";

        Dictionary <string,string> jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(json);

        foreach(var item in jsonObj.Keys){
            Console.WriteLine("Llave: {0} \r\n\t\t\t\tValor: {1}", item, jsonObj[item]);
        }

    }
}

Wanting to create Dynamic Properties would only add complexity, with this approach you can save the Keys you receive to have a Catalog of values that you can use to model the possible range of data you would receive from the service.

    
answered by 09.03.2017 в 19:59