How to Convert JSON object to Custom C# object?
Since we all love one liners code
Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
if we have class then use below.
Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(jsonString);
no class then use dynamic
var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);
A good way to use JSON in C# is with JSON.NET
Quick Starts & API Documentation from JSON.NET - Official site help you work with it.
An example of how to use it:
public class User
{
public User(string json)
{
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["user"];
name = (string) jUser["name"];
teamname = (string) jUser["teamname"];
email = (string) jUser["email"];
players = jUser["players"].ToArray();
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
// Use
private void Run()
{
string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}
To keep your options open, if you're using .NET 3.5 or later, here is a wrapped up example you can use straight from the framework using Generics. As others have mentioned, if it's not just simple objects you should really use JSON.net.
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
You'll need:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;