在 C# 中将对象转换为 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11345382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert object to JSON string in C#
提问by user595234
Possible Duplicate:
Turn C# object into a JSON string in .NET 4
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();
}
...
}
采纳答案by foson
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);
回答by Govind Malviya
Use .net inbuilt class JavaScriptSerializer
使用 .net 内置类JavaScriptSerializer
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(obj);

