如何使用C#将Class对象转换为JSON格式

时间:2015-11-09 07:20:38

标签: c# json json.net

我想使用C#Code

将继承的Class对象转换为Json格式

这是我要转换为json的继承类

public class RetrieveSanctionPartyListResponse : BaseResponse
    {
        public RetrieveSanctionPartyList RetrieveSanctionPartyList { get; set; }
    }

在上面的类中,这里有另一个类是该类的代码

 public class RetrieveSanctionPartyList
    {
        public string Spl { get; set; }
        public string Tech { get; set; }
        public string PartnerId { get; set; }
    }

继承类

public class BaseResponse
    {

        public bool Success { get; set; }

        public List<string> Messages { get; set; }

        public BaseResponse()
        {
            Messages = new List<string>();
        }

        public virtual string ToSerialize()
        {
            string txXML;
            using (var ms = new MemoryStream())
            {
                var ser = new DataContractSerializer(GetType());
                ser.WriteObject(ms, this);
                ms.Position = 0;
                var sr = new StreamReader(ms);
                txXML = sr.ReadToEnd();
                //txXML = "\"" + txXML.Replace("\"", "\\\"") + "\"";
                sr.Close();
            }
            return txXML;
        }
    }

3 个答案:

答案 0 :(得分:3)

使用Json.NET,您可以序列化类RetrieveSanctionPartyListResponse的实例:

var partyListResponse = new RetrieveSanctionPartyListResponse();
var serializedObject = JsonConvert.SerializeObject(partyListResponse);

答案 1 :(得分:1)

=== 更新 ===

(。Net 4.0或更高版本)将您的项目引用到System.Runtime.Serialization.dll

将课程更改为:

RetrieveSanctionPartyList.cs

[DataContract]
public class RetrieveSanctionPartyList
{
    [DataMember]
    public string Spl { get; set; }
    [DataMember]
    public string Tech { get; set; }
    [DataMember]
    public string PartnerId { get; set; }
}

BaseResponse.cs

[DataContract]
public class BaseResponse
{
    [DataMember]
    public bool Success { get; set; }

    [DataMember]
    public List<string> Messages { get; set; }

    public BaseResponse()
    {
        Messages = new List<string>();
    }

    public static T fromJson<T>(string json)
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer js = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(json));
        T obj = (T)js.ReadObject(ms);
        return obj;
    }

    public string toJson()
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer js = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType());
        MemoryStream ms = new MemoryStream();
        js.WriteObject(ms, this);
        ms.Position = 0;
        StreamReader sr = new StreamReader(ms);
        return sr.ReadToEnd();
    }

    public virtual void print()
    {
        Console.WriteLine("Class: " + this.GetType());
        Console.WriteLine("[Success] " + this.Success);
        foreach (string str in this.Messages)
            Console.WriteLine("[Messages] " + str);
    }
}

RetrieveSanctionPartyListResponse .cs

public class RetrieveSanctionPartyListResponse : BaseResponse
{
    [DataMember]
    public RetrieveSanctionPartyList RetrieveSanctionPartyList { get; set; }

    public override void print()
    {
        base.print();
        Console.WriteLine("[RetrieveSanctionPartyList.Spl] " + RetrieveSanctionPartyList.Spl);
        Console.WriteLine("[RetrieveSanctionPartyList.Tech] " + RetrieveSanctionPartyList.Tech);
        Console.WriteLine("[RetrieveSanctionPartyList.PartnerId] " + RetrieveSanctionPartyList.PartnerId);
    }
}

测试程序:

static void Main()
    {
        BaseResponse obj = new BaseResponse();
        obj.Messages.Add("4");
        obj.Messages.Add("2");
        obj.Messages.Add("3");
        obj.print();
        string json = obj.toJson();
        Console.WriteLine("Json: " + json);

        BaseResponse clone = BaseResponse.fromJson<BaseResponse>(json);
        Console.WriteLine("Clone: ");
        clone.print();

        RetrieveSanctionPartyListResponse child1 = new RetrieveSanctionPartyListResponse();
        child1.Success = true;
        child1.Messages.Add("Only one");
        RetrieveSanctionPartyList list = new RetrieveSanctionPartyList();
        list.Spl = "MySPL";
        list.PartnerId = "MyPartnerId";
        list.Tech = "MyTech";
        child1.RetrieveSanctionPartyList = list;
        child1.print();

        json = child1.toJson();
        Console.WriteLine("Json: " + json);

        RetrieveSanctionPartyListResponse cloneChild1 = BaseResponse.fromJson<RetrieveSanctionPartyListResponse>(json);
        Console.WriteLine("cloneChild1: ");
        cloneChild1.print();

        Console.ReadLine();
    }

输出继电器:

  

类:WindowsForms.BaseResponse

     

[成功]错误

     

[讯息] 4

     

[讯息] 2

     

[讯息] 3

     

Json:{“Messages”:[“4”,“2”,“3”],“成功”:false}

     

克隆:

     

类:WindowsForms.BaseResponse

     

[成功]错误

     

[讯息] 4

     

[讯息] 2

     

[讯息] 3

     

类:WindowsForms.RetrieveSanctionPartyListResponse

     

[成功]真实

     

[消息]只有一个

     

[RetrieveSanctionPartyList.Spl] MySPL

     

[RetrieveSanctionPartyList.Tech] MyTech

     

[RetrieveSanctionPartyList.PartnerId] MyPartnerId

     

Json:{“Messages”:[“Only one”],“Success”:true,“RetrieveSanctionPartyList”:{“Part

     

nerId “:” MyPartnerId”, “SPL”: “MySPL”, “技术”: “明泰”}}

     

cloneChild1:

     

类:WindowsForms.RetrieveSanctionPartyListResponse

     

[成功]真实

     

[消息]只有一个

     

[RetrieveSanctionPartyList.Spl] MySPL

     

[RetrieveSanctionPartyList.Tech] MyTech

     

[RetrieveSanctionPartyList.PartnerId] MyPartnerId

答案 2 :(得分:0)

将c#对象转换为JSON的另一种方法 - 通过JavaScriptSerializer

var data = $('.row').map(function() {
    var obj = {};
    $(this).find('input').each(function() {
        obj[this.name] = this.value;
    });
    return obj;
}).get();

有关DataContractJsonSerializer与JavaScriptSerializer之间差异的列表,请参阅here.