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;
        }
    }
Ajinkya Sawant
  • 100
  • 1
  • 13
  • 1
    See http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4 – Jan Thomä Nov 09 '15 at 07:22
  • Please explain what did you tried so far and where are you facing the problem? – Siva Gopal Nov 09 '15 at 07:25
  • I have done as given but it baserespose class is getting converted into JSON but not the main class RetrieveSanctionPartyListResponse – Ajinkya Sawant Nov 09 '15 at 07:26
  • While converting into JSON format. inherited class baseresponse is getting converted but cannot convert the main class RetrieveSanctionPartyListResponse – Ajinkya Sawant Nov 09 '15 at 07:27
  • Do you want to create XML or JSON? Your question says "JSON" but your code sample creates XML with `DataContractSerializer`. – dbc Nov 09 '15 at 07:40
  • Can you update your question to show how you are creating the JSON? Your code to create XML seems to be working perfectly. In fact if you replace `DataContractSerializer` with `DataContractJsonSerializer` that should work perfectly also. – dbc Nov 09 '15 at 07:46

3 Answers3

3

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

var partyListResponse = new RetrieveSanctionPartyListResponse();
var serializedObject = JsonConvert.SerializeObject(partyListResponse);
PMerlet
  • 2,568
  • 4
  • 23
  • 39
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

Community
  • 1
  • 1
HungPV
  • 489
  • 6
  • 19
  • 2
    In `ObjectToJson(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. – dbc Nov 09 '15 at 07:52
  • [here](http://csharp2json.azurewebsites.net/) is **online tool** to convert your `classes` to `json` format, hope helps someone. – Shaiju T Jan 25 '17 at 08:24
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.

Community
  • 1
  • 1
Jodi Supporter
  • 330
  • 1
  • 7