在C#中将对象转换为JSON字符串

use*_*234 49 c# json

可能重复:
将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)

  • @LexyFeito我看到没有人回答你的问题.使用:`var settings = new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()};``settings.Converters.Add(new StringEnumConverter());``var json = JsonConvert.SerializeObject(myReturnData,Formatting.Indented,settings);` (2认同)

Gov*_*iya 40

在.net内置类JavaScriptSerializer中使用.net

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);
Run Code Online (Sandbox Code Playgroud)