vyshak Shivakumara
vyshak Shivakumara

Reputation: 21

Deserialization of JSON in c#

I have the following JSON

{
    "employee" : {
        "property1" : "value1",
        "property2" : "value2",
        //...
    }
}

to a class like

public class employee
{
    public string property1{get;set;}
    public string property2{get;set;}
    //...
}

In my JSON if I need to add property3 then I need to make changes in my class too. How can I deserialize to a class even though if I change my JSON(adding another property like property3). The serialize/De-serialize techniques like newtonsoft.json is tightly coupled with the Class. Is there a better way/tool to deserialize these kind of JSON in portable class in c#?

Upvotes: 2

Views: 118

Answers (3)

vyshak Shivakumara
vyshak Shivakumara

Reputation: 21

If we can use " Dictionary<string,string> employee" the above json can be deserilized.

Upvotes: 0

Stanislav Berkov
Stanislav Berkov

Reputation: 6287

You can try .net's JavaScriptSerializer (System.Web.Script.Serialization.JavaScriptSerializer). If some field is added or removed it deserializes object normally.

namespace ConsoleApplication8
{
public class Person
{
    public int PersonID { get; set; }
    //public string Name { get; set; }
    public bool Registered { get; set; }
    public string s1 { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var s = "{\"PersonID\":1,\"Name\":\"Name1\",\"Registered\":true}";
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var o = serializer.Deserialize<Person>(s);
        ;
    }
}
}

Upvotes: 0

Palanikumar
Palanikumar

Reputation: 7150

Newtonsoft is not tightly coupled with strong types. You can deserialize the dynamic types too. See the similar question here (How to read the Json data without knowing the Key value)

Upvotes: 1

Related Questions