I'm serializing JSON, for an HttpClient PostAsync call, like this:
var value = JsonValueExtensions.CreateFrom(request);
var json = value.ToString();
Debug.WriteLine(json);
HttpContent content = new StringContent(json);
request being a POCO that I created with DataContract and DataMember attributes. Is this the correct way to do this? I tried instantiating ObjectContent however the ctor is not public. Thanks!
namespace SL_DataContractJsonSerializer
{
publicpartialclass Page : UserControl
{
public Page()
{
InitializeComponent();
}
//This uses an event handler, not SL data bindingvoid OnClick(object sender, EventArgs args)
{
txtOutput1.Text = "Create a User object and serialize it.";
string json = WriteFromObject();
txtOutput2.Text = json.ToString(); // Displays: {"Age":42,"Name":"Bob"}
txtOutput3.Text = "Deserialize the data to a User object.";
string jsonString = "{'Name':'Bill', 'Age':53}";
User deserializedUser = ReadToObject(jsonString);
txtOutput4.Text = deserializedUser.Name; // Displays: Bill
txtOutput5.Text = deserializedUser.Age.ToString(); // Displays: 53
}
// Create a User object and serialize it to a JSON stream.publicstaticstring WriteFromObject()
{
//Create User object.
User user = new User("Bob", 42);
//Create a stream to serialize the object to.
MemoryStream ms = new MemoryStream();
// Serializer the User object to the stream.
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
ser.WriteObject(ms, user);
byte[] json = ms.ToArray();
ms.Close();
return Encoding.UTF8.GetString(json, 0, json.Length);
}
// Deserialize a JSON stream to a User object.publicstatic User ReadToObject(string json)
{
User deserializedUser = new User();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType());
deserializedUser = ser.ReadObject(ms) as User;
ms.Close();
return deserializedUser;
}
}
[DataContract]
publicclass User
{
[DataMember]
publicstring Name { get; set; }
[DataMember]
publicint Age { get; set; }
public User() { }
public User(string newName, int newAge)
{
Name = newName;
Age = newAge;
}
}
}
I write my own media type formatters - for both XML and JSON flavours. I write out the XML using LINQ to XML, and the JSON using JSON.NET's LINQ to JSON.
The trouble with having the framework do automatic serialization of a DTO / data contract for you is that it's an incredibly brittle solution.
For further discussion on why formatters are the best bet, see
here.
I posted another question yesterday regarding deserializing ISO dates in JSON. The solution that was presented is similiar to your answer. See here http://tro.pe/An5ips
Media type formatters are a total win, and one of the best things about ASP.NET Web API is that it treats them as a first-class concept. This has been evident since Glenn Block's
first posts on WCF Web API.
A REST API should never have “typed” resources that are significant to the client
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media
types
I maintain that these are good and sensible rules to follow even if you don't want to be RESTful, since they aid decoupling.
A more opinionated framework than ASP.NET Web API might go so far as to not support any form of automatic DTO / data contract serialization (for JSON or XML), and force the developer to write their own media type formatters for all resource representations.
Such a framework could be built on top of ASP.NET Web API.
Or you could adopt this more constrained style with plain vanilla ASP.NET Web API, as I do. See Mike Amundsen's book on building Hypermedia APIs for more on this subject.
Perhaps I should have clarified my original question. I am CONSUMING someone else's API. I'm clientside, NOT serverside. Perhaps that changes the nature of the problem.
Er, yes, I see now that you did mention "HttpClient"! Well...
Json.NET is a great thing for all things JSON, imo. Installable via NuGet. Here's
Hanselman on the subject.
And, er, when you code server side, media type formatters are your friend!
bittondb
Member
17 Points
18 Posts
Best Practices for JSON Serialization
Mar 01, 2012 08:01 PM|LINK
I'm serializing JSON, for an HttpClient PostAsync call, like this:
var value = JsonValueExtensions.CreateFrom(request); var json = value.ToString(); Debug.WriteLine(json); HttpContent content = new StringContent(json);request being a POCO that I created with DataContract and DataMember attributes. Is this the correct way to do this? I tried instantiating ObjectContent however the ctor is not public. Thanks!
Shellymn
Contributor
2622 Points
485 Posts
Re: Best Practices for JSON Serialization
Mar 01, 2012 08:12 PM|LINK
I am using DataContractJsonSerializer class for serializing JSON ....
bittondb
Member
17 Points
18 Posts
Re: Best Practices for JSON Serialization
Mar 01, 2012 08:28 PM|LINK
Can you share some code? I was thinking about using a JsonMediaTypeFormatter
Shellymn
Contributor
2622 Points
485 Posts
Re: Best Practices for JSON Serialization
Mar 01, 2012 08:32 PM|LINK
bittondb
Member
17 Points
18 Posts
Re: Best Practices for JSON Serialization
Mar 01, 2012 08:36 PM|LINK
Thanks!
awebb
Member
204 Points
91 Posts
Re: Best Practices for JSON Serialization
Mar 02, 2012 06:26 AM|LINK
I write my own media type formatters - for both XML and JSON flavours. I write out the XML using LINQ to XML, and the JSON using JSON.NET's LINQ to JSON.
The trouble with having the framework do automatic serialization of a DTO / data contract for you is that it's an incredibly brittle solution.
For further discussion on why formatters are the best bet, see here.
bittondb
Member
17 Points
18 Posts
Re: Best Practices for JSON Serialization
Mar 02, 2012 01:27 PM|LINK
I posted another question yesterday regarding deserializing ISO dates in JSON. The solution that was presented is similiar to your answer. See here http://tro.pe/An5ips
awebb
Member
204 Points
91 Posts
Re: Best Practices for JSON Serialization
Mar 02, 2012 02:42 PM|LINK
Media type formatters are a total win, and one of the best things about ASP.NET Web API is that it treats them as a first-class concept. This has been evident since Glenn Block's first posts on WCF Web API.
Media type formatters allow you to follow two of Roy Fielding's rules for RESTful web services:-
I maintain that these are good and sensible rules to follow even if you don't want to be RESTful, since they aid decoupling.
A more opinionated framework than ASP.NET Web API might go so far as to not support any form of automatic DTO / data contract serialization (for JSON or XML), and force the developer to write their own media type formatters for all resource representations. Such a framework could be built on top of ASP.NET Web API.
Or you could adopt this more constrained style with plain vanilla ASP.NET Web API, as I do. See Mike Amundsen's book on building Hypermedia APIs for more on this subject.
bittondb
Member
17 Points
18 Posts
Re: Best Practices for JSON Serialization
Mar 02, 2012 03:20 PM|LINK
Perhaps I should have clarified my original question. I am CONSUMING someone else's API. I'm clientside, NOT serverside. Perhaps that changes the nature of the problem.
awebb
Member
204 Points
91 Posts
Re: Best Practices for JSON Serialization
Mar 02, 2012 03:49 PM|LINK
Er, yes, I see now that you did mention "HttpClient"! Well... Json.NET is a great thing for all things JSON, imo. Installable via NuGet. Here's Hanselman on the subject.
And, er, when you code server side, media type formatters are your friend!