Quantcast
Channel: String JSON a Objeto
Viewing all articles
Browse latest Browse all 5

String JSON a Objeto

$
0
0

Hola, cuando en un JSON te devuelven elementos que son numéricos se deben deserializar a Dictionary ya que ningún lenguaje de la plataforma .NET te permite crear una clase cuyo nombre sea un número.

Te recomiendo eches un ojo a esta página para generar tus clases serializables QuickType

Usando tu texto Json y generando las clases tenemos un ejemplo así

// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using QuickType;
//
//    var welcome = Welcome.FromJson(jsonString);

namespace QuickType
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Welcome
    {
        [JsonProperty("nombre")]
        public string Nombre { get; set; }

        [JsonProperty("usuario")]
        public string Usuario { get; set; }
    }

    public partial class Welcome
    {
        public static Dictionary<string, Welcome> FromJson(string json) => JsonConvert.DeserializeObject<Dictionary<string, Welcome>>(json, QuickType.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Dictionary<string, Welcome> self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

Cambia los namespaces y el nombre de la clase obviamente.

El ejemplo que se indica para deserialziar es así

var welcome = Welcome.FromJson(jsonString);


Si se solucionó tu consulta no olvides marcar la respuesta. Si te ayudó, vótala como útil. Saludos


Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>