Reynaldo Granados
Reynaldo Granados

Reputation: 51

How to Serialize Json to Object in C# without use NewtonSoft

i tried to Serialize a Json to a "x" class, but i can't get this object with values from my Json. I want to do this without use NewtonSoft. Somebody can help?

{"Data":{"RI":{"Node":1,"Subnode":1 }},"RU":{"Node":2,"Subnode":2 }}}



public class RootObject{
    public List<Data> Data {get; set;}


    public static Data Deserialize(string jsonData){
        JavaScriptSerializer ser = new JavaScriptSerializer();
        RootObject rootObj = ser.Deserialize<RootObject>(jsonData);    return rootObj;
    }
}

public class Data{
    public RI RI {get; set;}
    public RU RU {get; set;}
}

public class RI{
    public int Node {get; set;}
    public int Subnode {get; set;}
}
public class RU{
    public int Node {get; set;}
    public int Subnode {get; set;}
}

Upvotes: 2

Views: 1200

Answers (1)

O. Jones
O. Jones

Reputation: 108696

WCF has some JSON stuff in it.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-serialize-and-deserialize-json-data

Ya need to adorn your classes with [DataContract] and [DataMember]. Something like this.

[DataContract]
public class Data{
    public RI RI {get; set;}
    public RU RU {get; set;}
}

[DataMember]
public class RI{
    public int Node {get; set;}
    public int Subnode {get; set;}
}

[DataMember]
public class RU{
    public int Node {get; set;}
    public int Subnode {get; set;}
}

You didn't show your Node and Subnode classes; you will have to make them into [DataMember] classes too.

Then you can put the JSON into a stream something like this:

var data = new Data();
...
/* populate data somehow or other */
...
MemoryStream str = new MemoryStream();  
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
...
ser.WriteObject(str, data);   
...
/* read back that stream */
str.Position = 0;  
StreamReader sr = new StreamReader(st);  
Console.WriteLine(sr.ReadToEnd());   /* or something else useful */

More fun than developers should be allowed to have.

Upvotes: 1

Related Questions