转换对象J​​SON字符串在C# [英] Convert object to JSON string in C#

查看:356
本文介绍了转换对象J​​SON字符串在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
打开C#对象转换成JSON字符串在.NET 4






在Java,我有一个代码,Java对象转换成JSON字符串。如何做到在C#中的相似?这JSON库我应该用?



感谢。



JAVA代码



 进口net.sf.json.JSONArray; 
进口net.sf.json.JSONObject;

公共类ReturnData {
INT总额;

名单,LT; ExceptionReport> exceptionReportList;

公共字符串的getJSON(){
JSONObject的JSON =新的JSONObject();

json.put(TOTALCOUNT,总数);

JSONArray jsonArray =新JSONArray();
为(ExceptionReport报告:exceptionReportList){
的JSONObject jsonTmp =新的JSONObject();
jsonTmp.put(reportId,report.getReportId());
jsonTmp.put(消息,report.getMessage());
jsonArray.add(jsonTmp);
}

json.put(报告,JSONArray),其中;
返回json.toString();
}

}


解决方案

我已经使用 Newtonsoft JSON.NET (的文档),它允许你创建一个类/对象,填充字段,如序列化JSON。

 公共类ReturnData 
{
公众诠释TOTALCOUNT {搞定;组; }
公开名单< ExceptionReport>报告{搞定;组; }
}

公共类ExceptionReport
{
公众诠释reportId {搞定;组; }
公共字符串消息{搞定;组; }
}


JSON字符串= JsonConvert.SerializeObject(myReturnData);


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 ?

Thanks.

JAVA code

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

解决方案

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as 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);

这篇关于转换对象J​​SON字符串在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆