Cómo crear una cadena JSON en C#


Acabo de usar el XmlWriter para crear algo de XML para enviar de vuelta en una respuesta HTTP. Cómo crearías una cadena JSON. Asumo que solo usaría un stringbuilder para construir la cadena JSON y formatear su respuesta como JSON?

Author: Mark Rushakoff, 2009-06-29

12 answers

Puede usar la clase JavaScriptSerializer, verifique este artículo para construir un método de extensión útil.

Código del artículo:

namespace ExtensionMethods
{
    public static class JSONHelper
    {
        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJSON(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }
    }
}

Uso:

using ExtensionMethods;

...

List<Person> people = new List<Person>{
                   new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
                   new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
                   };


string jsonString = people.ToJSON();
 225
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-08 20:55:44

Usando Newtonsoft.Json lo hace realmente más fácil:

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);

Documentación: Serialización y deserialización de JSON

 321
Author: Orr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-30 22:12:31

Esta biblioteca es muy buena para JSON desde C #

Http://james.newtonking.com/pages/json-net.aspx

 18
Author: Hugoware,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-29 00:30:40

Este fragmento de código utiliza el DataContractJsonSerializer de System.Ejecución.Serialización.Json en. NET 3.5.

public static string ToJson<T>(/* this */ T value, Encoding encoding)
{
    var serializer = new DataContractJsonSerializer(typeof(T));

    using (var stream = new MemoryStream())
    {
        using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
        {
            serializer.WriteObject(writer, value);
        }

        return encoding.GetString(stream.ToArray());
    }
}
 10
Author: Joe Chung,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-29 00:55:56

Echa un vistazo a http://www.codeplex.com/json / para el json-net.proyecto aspx. Por qué reinventar la rueda?

 7
Author: Josh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-29 00:32:18

También puede probar mi ServiceStack JsonSerializer es el serializador JSON de.NET más rápido en este momento. Soporta serialización de DataContracts, cualquier tipo POCO, Interfaces, objetos de enlace tardío incluyendo tipos anónimos, etc.

Ejemplo básico

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json); 

Nota: Solo use Microsofts JavaScriptSerializer si el rendimiento no es importante para usted, ya que he tenido que dejarlo fuera de mis puntos de referencia ya que es hasta 40x-100x más lento que el otro JSON serializers.

 7
Author: mythz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-19 16:49:01

Si necesita un resultado complejo (incrustado) cree su propia estructura:

class templateRequest
{
    public String[] registration_ids;
    public Data data;
    public class Data
    {
        public String message;
        public String tickerText;
        public String contentTitle;
        public Data(String message, String tickerText, string contentTitle)
        {
            this.message = message;
            this.tickerText = tickerText;
            this.contentTitle = contentTitle;
        }                
    };
}

Y luego puede obtener una cadena JSON llamando a

List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");

string json = new JavaScriptSerializer().Serialize(request);

El resultado será así:

json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"

Espero que ayude!

 6
Author: Subtle Fox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-01 08:48:14

Si no puede o no quiere usar los dos serializadores JSON integrados (JavaScriptSerializer y DataContractJsonSerializer) puede probar la biblioteca JsonExSerializer-la uso en varios proyectos y funciona bastante bien.

 5
Author: Tamas Czinege,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-29 00:47:01

Si está intentando crear un servicio web para servir datos sobre JSON a una página web, considere usar el ASP.NET Ajax toolkit:

Http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

Convertirá automáticamente sus objetos servidos a través de un servicio web a json y creará la clase proxy que puede usar para conectarse a él.

 2
Author: Eduardo Scoz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-29 00:28:49

El DataContractJsonSerializer hará todo por usted con la misma facilidad que el XmlSerializer. Es trivial usar esto en una aplicación web. Si está utilizando WCF, puede especificar su uso con un atributo. La familia DataContractSerializer también es muy rápida.

 1
Author: Steve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-29 00:49:09

He descubierto que no necesita el serializador en absoluto. Si devuelve el objeto como una lista. Permítanme poner un ejemplo.

En nuestro asmx obtenemos los datos usando la variable que pasamos

// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> GetData(int id) 
{
    var data = from p in db.property 
               where p.id == id 
               select new latlon
               {
                   lat = p.lat,
                   lon = p.lon

               };
    return data.ToList();
}

public class latlon
{
    public string lat { get; set; }
    public string lon { get; set; }
}

A continuación, utilizando jquery accedemos al servicio, pasando a lo largo de esa variable.

// get latlon
function getlatlon(propertyid) {
var mydata;

$.ajax({
    url: "getData.asmx/GetLatLon",
    type: "POST",
    data: "{'id': '" + propertyid + "'}",
    async: false,
    contentType: "application/json;",
    dataType: "json",
    success: function (data, textStatus, jqXHR) { //
        mydata = data;
    },
    error: function (xmlHttpRequest, textStatus, errorThrown) {
        console.log(xmlHttpRequest.responseText);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
return mydata;
}

// call the function with your data
latlondata = getlatlon(id);

Y obtenemos nuestra respuesta.

{"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}
 1
Author: Prescient,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-08 13:36:55

Uso de Codificación

Simple object to JSON Array EncodeJsObjectArray ()

public class dummyObject
{
    public string fake { get; set; }
    public int id { get; set; }

    public dummyObject()
    {
        fake = "dummy";
        id = 5;
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append('[');
        sb.Append(id);
        sb.Append(',');
        sb.Append(JSONEncoders.EncodeJsString(fake));
        sb.Append(']');

        return sb.ToString();
    }
}

dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();

dummys[0].fake = "mike";
dummys[0].id = 29;

string result = JSONEncoders.EncodeJsObjectArray(dummys);

Resultado: [[29,"mike"], [5,"dummy"]]

Bastante uso

Pretty print JSON Array PrettyPrintJson () string extension method

string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();

Los resultados son:

[
   14,
   4,
   [
      14,
      "data"
   ],
   [
      [
         5,
         "10.186.122.15"
      ],
      [
         6,
         "10.186.122.16"
      ]
   ]
]
 1
Author: Sudhakar Rao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-21 00:53:52