RSS Feed for This PostCurrent Article

Serialize .NET Object to JSON String

Download Source

This is another variation of my previous post, Serialize Java Object to JSON String. Here I rewrite the code using Json.NET

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace Json.Tests
{
class Person
{
private String name;
private int age;
private String email;

public Person()
{
}

public Person(String name, int age, String email)
{
this.name = name;
this.age = age;
this.email = email;
}

public String Name
{
get
{
return name;
}
set
{
name = value;
}
}

public int Age
{
get
{
return age;
}
set
{
age = value;
}
}

public String Email
{
get
{
return email;
}
set
{
email = value;
}
}

public static void Main()
{
// Serialize
Person person = new Person(“jason”, 30, “jason@hotmail.com”);
string json = JavaScriptConvert.SerializeObject(person);
Console.WriteLine(json);

// Deserialize
Person newPerson = JavaScriptConvert.DeserializeObject<Person>(json);
Console.WriteLine(newPerson.Name);
Console.WriteLine(newPerson.Age);
Console.WriteLine(newPerson.Email);
Console.ReadLine();

}

}
}

Sample output:

{"Name":"jason","Age":30,"Email":"jason@hotmail.com"}
jason
30
jason@hotmail.com


Trackback URL


Sorry, comments for this entry are closed at this time.