在c# [duplicate]中将对象转换为JSON字符串

时间:2021-12-17 21:33:01

Possible Duplicate:
Turn C# object into a JSON string in .NET 4

可能重复:在。net 4中将c#对象转换成JSON字符串

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 ?

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

Thanks.

谢谢。

JAVA code

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

2 个解决方案

#1


79  

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

我使用了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);

#2


36  

Use .net inbuilt class JavaScriptSerializer

使用。net内建类JavaScriptSerializer

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

#1


79  

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

我使用了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);

#2


36  

Use .net inbuilt class JavaScriptSerializer

使用。net内建类JavaScriptSerializer

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