Possible Duplicate:
Turn C# object into a JSON string in .NET 4
In the Java, I have a code to convert java object to JSON string. How to do the similar in the C# ? which JSON library I should use ?
Thanks.
JAVA code
import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class ReturnData { int total; List<ExceptionReport> exceptionReportList; public String getJSon(){ JSONObject json = new JSONObject(); json.put("totalCount", total); JSONArray jsonArray = new JSONArray(); for(ExceptionReport report : exceptionReportList){ JSONObject jsonTmp = new JSONObject(); jsonTmp.put("reportId", report.getReportId()); jsonTmp.put("message", report.getMessage()); jsonArray.add(jsonTmp); } json.put("reports", jsonArray); return json.toString(); } ... }
Using JsonConverter JsonConvert class has a method to convert to and from JSON string, SerializeObject() and DeserializeObject() respectively. It can be used where we won't to convert to and from a JSON string.
We do this, because both the Key and Value has to be of type string, as a requirement for serialization of a Dictionary . var json = new JavaScriptSerializer(). Serialize(convertedDictionary); //You can then serialize the Dictionary, as both the Key and Value is of type string, which is required for serialization.
This sample uses JsonPropertyAttribute to change the names of properties when they are serialized to JSON. Types. public class Videogame { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }
I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.
public class ReturnData { public int totalCount { get; set; } public List<ExceptionReport> reports { get; set; } } public class ExceptionReport { public int reportId { get; set; } public string message { get; set; } } string json = JsonConvert.SerializeObject(myReturnData);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With