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 に答える