50

可能重复:
在 .NET 4 中将 C# 对象转换为 JSON 字符串

在 Java 中,我有一个将 java 对象转换为 JSON 字符串的代码。如何在 C# 中做类似的事情?我应该使用哪个 JSON 库?

谢谢。

JAVA代码

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

2 回答 2

106

我使用过Newtonsoft JSON.NET文档),它允许您创建类/对象、填充字段并序列化为 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);
于 2012-07-05T13:35:37.733 回答
40

使用 .net 内置类JavaScriptSerializer

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);
于 2012-07-05T13:33:18.190 回答