I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the JSON string and them format your response as JSON?
问题:
回答1:
You could use the JavaScriptSerializer class, check this article to build an useful extension method.
Code from article:
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);
}
}
}
Usage:
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();
回答2:
Using Newtonsoft.Json makes it really easier:
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);
Documentation: Serializing and Deserializing JSON
回答3:
This library is very good for JSON from C#
http://james.newtonking.com/pages/json-net.aspx
回答4:
This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .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());
}
}
回答5:
Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?
回答6:
You can also try my ServiceStack JsonSerializer it\'s the fastest .NET JSON serializer at the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name=\"Joe Bloggs\", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I\'ve had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.
回答7:
If you need complex result (embedded) create your own structure:
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;
}
};
}
and then you can obtain JSON string with calling
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);
The result will be like this:
json = \"{\\\"registration_ids\\\":[\\\"id1\\\",\\\"id2\\\"],\\\"data\\\":{\\\"message\\\":\\\"Your message\\\",\\\"tickerText\\\":\\\"Your ticket\\\",\\\"contentTitle\\\":\\\"Your content\\\"}}\"
Hope it helps!
回答8:
If you can\'t or don\'t want to use the two built-in JSON serializers (JavaScriptSerializer and DataContractJsonSerializer) you can try the JsonExSerializer library - I use it in a number of projects and works quite well.
回答9:
If you\'re trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.
回答10:
The DataContractJSONSerializer will do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.
回答11:
I\'ve found that you don\'t need the serializer at all. If you return the object as a List. Let me use an example.
In our asmx we get the data using the variable we passed along
// 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; }
}
Then using jquery we access the service, passing along that 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);
And we get our response.
{\"d\":[{\"__type\":\"MapData+latlon\",\"lat\":\"40.7031420\",\"lon\":\"-80.6047970}]}
回答12:
Encode Usage
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);
Result: [[29,\"mike\"],[5,\"dummy\"]]
Pretty Usage
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();
Results is:
[
14,
4,
[
14,
\"data\"
],
[
[
5,
\"10.186.122.15\"
],
[
6,
\"10.186.122.16\"
]
]
]