una recorrer por objeto leer enviar ejecutar desde crear consumir construir como cadena c# json json.net deserialization

recorrer - ¿Cómo puedo analizar JSON con C#?



enviar json por post c# (11)

Tengo el siguiente código:

var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);

La entrada en responsecontent es JSON, pero no se analiza correctamente en un objeto. ¿Cómo debo deserializarlo adecuadamente?


Aquí hay algunas opciones sin usar bibliotecas de terceros:

// For that you will need to add reference to System.Runtime.Serialization var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas()); // For that you will need to add reference to System.Xml and System.Xml.Linq var root = XElement.Load(jsonReader); Console.WriteLine(root.XPathSelectElement("//Name").Value); Console.WriteLine(root.XPathSelectElement("//Address/State").Value); // For that you will need to add reference to System.Web.Helpers dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"); Console.WriteLine(json.Name); Console.WriteLine(json.Address.State);

Vea el enlace para obtener más información sobre System.Web.Helpers.Json .

Actualización : Hoy en día, la forma más fácil de obtener Web.Helpers es usar el paquete NuGet .

Si no le importan las versiones anteriores de Windows, puede usar las clases del espacio de nombres Windows.Data.Json :

// minimum supported version: Win 8 JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject(); Console.WriteLine(root["Name"].GetString()); Console.WriteLine(root["Address"].GetObject()["State"].GetString());


Como se respondió aquí, ¿ Deserializar JSON en un objeto dinámico C #?

Es bastante simple usar Json.NET:

dynamic stuff = JsonConvert.DeserializeObject("{ ''Name'': ''Jon Smith'', ''Address'': { ''City'': ''New York'', ''State'': ''NY'' }, ''Age'': 42 }"); string name = stuff.Name; string address = stuff.Address.City;

O utilizando Newtonsoft.Json.Linq:

dynamic stuff = JObject.Parse("{ ''Name'': ''Jon Smith'', ''Address'': { ''City'': ''New York'', ''State'': ''NY'' }, ''Age'': 42 }"); string name = stuff.Name; string address = stuff.Address.City;


Creo que la mejor respuesta que he visto ha sido @MD_Sayem_Ahmed.

Tu pregunta es "¿Cómo puedo analizar a Json con C #", pero parece que quieres decodificar a Json? Si quieres decodificarlo, la respuesta de Ahmed es buena.

Si está intentando lograr esto en ASP.NET Web Api, la forma más sencilla es crear un objeto de transferencia de datos que contenga los datos que desea asignar:

public class MyDto{ public string Name{get; set;} public string Value{get; set;} }

Simplemente agregue la aplicación / encabezado json a su solicitud (si está utilizando Fiddler, por ejemplo). Luego, usaría esto en la API web de ASP.NET de la siguiente manera:

//controller method -- assuming you want to post and return data public MyDto Post([FromBody] MyDto myDto){ MyDto someDto = myDto; /*ASP.NET automatically converts the data for you into this object if you post a json object as follows: { "Name": "SomeName", "Value": "SomeValue" } */ //do some stuff }

Esto me ayudó mucho cuando estaba trabajando en mi Web Api y me hizo la vida muy fácil.


Lo siguiente del sitio msdn debería ayudar a proporcionar alguna funcionalidad nativa para lo que está buscando. Tenga en cuenta que está especificado para Windows 8. A continuación se detalla uno de los ejemplos del sitio.

JsonValue jsonValue = JsonValue.Parse("{/"Width/": 800, /"Height/": 600, /"Title/": /"View from 15th Floor/", /"IDs/": [116, 943, 234, 38793]}"); double width = jsonValue.GetObject().GetNamedNumber("Width"); double height = jsonValue.GetObject().GetNamedNumber("Height"); string title = jsonValue.GetObject().GetNamedString("Title"); JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");

Utiliza el espacio de nombres Windows.Data.Json .


Otra solución nativa para esto, que no requiere ninguna biblioteca de terceros, sino una referencia a System.Web.Extensions es el JavaScriptSerializer. Esta no es una característica nueva pero muy desconocida incorporada allí desde 3.5.

using System.Web.Script.Serialization;

..

JavaScriptSerializer serializer = new JavaScriptSerializer(); objectString = serializer.Serialize(new MyObject());

y de vuelta

MyObject o = serializer.Deserialize<MyObject>(objectString)


Prueba el siguiente código:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL"); JArray array = new JArray(); using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) { JavaScriptSerializer js = new JavaScriptSerializer(); var objText = reader.ReadToEnd(); JObject joResponse = JObject.Parse(objText); JObject result = (JObject)joResponse["result"]; array = (JArray)result["Detail"]; string statu = array[0]["dlrStat"].ToString(); }


Si .NET 4 está disponible para usted, visite: http://visitmix.com/writings/the-rise-of-json (archive.org)

Aquí hay un fragmento de ese sitio:

WebClient webClient = new WebClient(); dynamic result = JsonValue.Parse(webClient.DownloadString("https://api.foursquare.com/v2/users/self?oauth_token=XXXXXXX")); Console.WriteLine(result.response.user.firstName);

Esa última consola.WriteLine es bastante dulce ...


Supongo que no está utilizando Json.NET (paquete Newtonsoft.Json NuGet). Si este es el caso, entonces deberías intentarlo.

Tiene las siguientes características:

  1. LINQ a JSON
  2. El JsonSerializer para convertir rápidamente sus objetos .NET a JSON y viceversa
  3. Json.NET puede opcionalmente producir JSON con sangría y bien formateado para la depuración o la visualización
  4. Atributos como JsonIgnore y JsonProperty se pueden agregar a una clase para personalizar cómo se serializa una clase
  5. Capacidad para convertir JSON desde y hacia XML
  6. Soporta múltiples plataformas: .NET, Silverlight y Compact Framework

Mira el example abajo. En este ejemplo, la clase example se usa para convertir un objeto desde y hacia JSON. Tiene dos métodos estáticos para este propósito. Son SerializeObject(Object obj) y DeserializeObject<T>(String json) :

Product product = new Product(); product.Name = "Apple"; product.Expiry = new DateTime(2008, 12, 28); product.Price = 3.99M; product.Sizes = new string[] { "Small", "Medium", "Large" }; string json = JsonConvert.SerializeObject(product); //{ // "Name": "Apple", // "Expiry": "2008-12-28T00:00:00", // "Price": 3.99, // "Sizes": [ // "Small", // "Medium", // "Large" // ] //} Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);


System.Json funciona ahora ...

Instale nuget https://www.nuget.org/packages/System.Json

PM> Install-Package System.Json -Version 4.5.0

Muestra :

// PM>Install-Package System.Json -Version 4.5.0 using System; using System.Json; namespace NetCoreTestConsoleApp { class Program { static void Main(string[] args) { // Note that json keys are case sensitive, a is not same as A. // Json Sample string jsonString = "{/"a/": 1,/"b/": /"string value/",/"c/":[{/"Value/": 1}, {/"Value/": 2,/"SubObject/":[{/"SubValue/":3}]}]}"; // Verify your json if you get any errors here JsonValue json = JsonValue.Parse(jsonString); // int test if (json.ContainsKey("a")) { int a = json["a"]; // type already set to int Console.WriteLine("json[/"a/"]" + " = " + a); } // string test if (json.ContainsKey("b")) { string b = json["b"]; // type already set to string Console.WriteLine("json[/"b/"]" + " = " + b); } // object array test if (json.ContainsKey("c") && json["c"].JsonType == JsonType.Array) { // foreach loop test foreach (JsonValue j in json["c"]) { Console.WriteLine("j[/"Value/"]" + " = " + j["Value"].ToString()); } // multi level key test Console.WriteLine("json[/"c/"][0][/"Value/"]" + " = " + json["c"][0]["Value"].ToString()); Console.WriteLine("json[/"c/"][0][/"Value/"]" + " = " + json["c"][1]["Value"].ToString()); Console.WriteLine("json[/"c/"][1][/"SubObject/"][0][/"SubValue/"]" + " = " + json["c"][1]["SubObject"][0]["SubValue"].ToString()); } Console.WriteLine(); Console.Write("Press any key to exit."); Console.ReadKey(); } } }



var result = controller.ActioName(objParams); IDictionary<string, object> data = (IDictionary<string, object>)new System.Web.Routing.RouteValueDictionary(result.Data); Assert.AreEqual("Table already exists.", data["Message"]);