We can use JsonWriter to return a JSON representation of any .Net object as displayed below.
public class Person
{
public Int Id {set ; get;}
public String Name{set ; get;}
public List<PhoneNumbers> Contacts{set ; get;}
public String ToJSONRepresentation()
{
StringBuilder stringBuilder = new StringBuilder();
JsonWriter jsonWriter = new JsonTextWriter(new StringWriter(stringBuilder));
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("id");
jsonWriter.WriteValue(this.Id);
jsonWriter.WritePropertyName("name");
jsonWriter.WriteValue(this.Name);
jsonWriter.WritePropertyName("phonenumbers");
jsonWriter.WriteStartArray();
int i=0;
for (i = 0; i < Contacts.Count; i++)
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("homePhone");
jsonWriter.WriteValue(addresses[i].homePhone);
jsonWriter.WritePropertyName("workPhone");
jsonWriter.WriteValue(addresses[i].workPhone);
jsonWriter.WritePropertyName("mobilePhone");
jsonWriter.WriteValue(addresses[i].mobilePhone);
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndArray();
jsonWriter.WriteEndObject();
return stringBuilder.ToString();
}
}
}
Cheers
Samitha