Convert object to JSON string in C#

C#Json

C# Problem Overview


> 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();
	}
    ...
}

C# Solutions


Solution 1 - C#

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);

Solution 2 - C#

Use .net inbuilt class JavaScriptSerializer

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser595234View Question on Stackoverflow
Solution 1 - C#fosonView Answer on Stackoverflow
Solution 2 - C#Govind MalviyaView Answer on Stackoverflow