可能重复:
将C#对象转换为.NET 4中的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();
}
...
}
Run Code Online (Sandbox Code Playgroud)
fos*_*son 99
我使用过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);
Run Code Online (Sandbox Code Playgroud)
Gov*_*iya 40
在.net内置类JavaScriptSerializer中使用.net
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(obj);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
247324 次 |
| 最近记录: |