【问题标题】:Convert object to JSON string in C# [duplicate]在C#中将对象转换为JSON字符串[重复]
【发布时间】:2012-07-05 22:04:16
【问题描述】:

可能重复:
Turn C# object into a JSON string in .NET 4

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

【问题讨论】:

  • 您应该在 C# 中尝试一下,并向我们展示您正在尝试的代码。正如所写,这个问题只不过是一个远离答案的谷歌搜索,并没有增加价值。请编辑您的问题以包含您在 C# 中尝试过的内容以及无效的内容。
  • @George Stocker 他在询问有关序列化的问题,而您正在显示反序列化的副本,为什么?
  • @GovindKamalaPrakashMalviya 在无数重复中,我误读并选择了错误的那个。感谢您了解这一点。

标签: c# json


【解决方案1】:

我使用过Newtonsoft JSON.NET (Documentation) 它允许您创建类/对象、填充字段并序列化为 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);

【讨论】:

  • 您好,这个答案有效,但有没有办法将对象序列化为 javascript 格式,如 new {Name = "Myname"} 将被序列化为 {name: "MyName"}。谢谢
  • @LexyFeito 我看没有人回答你的问题。使用:var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };settings.Converters.Add(new StringEnumConverter());var json = JsonConvert.SerializeObject(myReturnData, Formatting.Indented, settings);
  • 我已经按照这个工作正常但是如果数据或对象包含更多内容,那么它会抛出内存不足异常。如何处理?
  • @MdAslam 请按照stackoverflow.com/help/how-to-ask 的说明提出新问题
【解决方案2】:

使用 .net 内置类JavaScriptSerializer

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

【讨论】:

  • 如何处理'json.put("totalCount", total); ' ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
相关资源
最近更新 更多