0

I Want to convert inherited Class object into Json Format using C# Code

Here is the inherited class that i am converting into json

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

In the above class it has another class here is the code of that class

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

Inherited class

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;
        }
    }
6
  • 1
    See stackoverflow.com/questions/6201529/… Commented Nov 9, 2015 at 7:22
  • Please explain what did you tried so far and where are you facing the problem? Commented Nov 9, 2015 at 7:25
  • I have done as given but it baserespose class is getting converted into JSON but not the main class RetrieveSanctionPartyListResponse Commented Nov 9, 2015 at 7:26
  • While converting into JSON format. inherited class baseresponse is getting converted but cannot convert the main class RetrieveSanctionPartyListResponse Commented Nov 9, 2015 at 7:27
  • Do you want to create XML or JSON? Your question says "JSON" but your code sample creates XML with DataContractSerializer. Commented Nov 9, 2015 at 7:40

3 Answers 3

3

Using Json.NET, you can serialize an instance of your class RetrieveSanctionPartyListResponse :

var partyListResponse = new RetrieveSanctionPartyListResponse();
var serializedObject = JsonConvert.SerializeObject(partyListResponse);
Sign up to request clarification or add additional context in comments.

Comments

1

=== UPDATE ===

(.Net 4.0 or higher) Reference your project to System.Runtime.Serialization.dll

Change your classes to:

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

Test program:

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

Ouput:

Class: WindowsForms.BaseResponse

[Success] False

[Messages] 4

[Messages] 2

[Messages] 3

Json: {"Messages":["4","2","3"],"Success":false}

Clone:

Class: WindowsForms.BaseResponse

[Success] False

[Messages] 4

[Messages] 2

[Messages] 3

Class: WindowsForms.RetrieveSanctionPartyListResponse

[Success] True

[Messages] Only one

[RetrieveSanctionPartyList.Spl] MySPL

[RetrieveSanctionPartyList.Tech] MyTech

[RetrieveSanctionPartyList.PartnerId] MyPartnerId

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

nerId":"MyPartnerId","Spl":"MySPL","Tech":"MyTech"}}

cloneChild1:

Class: WindowsForms.RetrieveSanctionPartyListResponse

[Success] True

[Messages] Only one

[RetrieveSanctionPartyList.Spl] MySPL

[RetrieveSanctionPartyList.Tech] MyTech

[RetrieveSanctionPartyList.PartnerId] MyPartnerId

2 Comments

In ObjectToJson<T>(T obj) you may want to do new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()), otherwise obj might only get serialized as its base class - which seems to be the problem OP describes in comments.
here is online tool to convert your classes to json format, hope helps someone.
0

Yet another way to convert a c# object to JSON - via JavaScriptSerializer

var serializer = new JavaScriptSerializer();            
var json = serializer.Serialize(new {Field1="Value1"});

For a list of differences between DataContractJsonSerializer and JavaScriptSerializer see here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.