2

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#?

Alexey Nis
  • 471
  • 3
  • 9
  • 1
    One way would be a custom JSON-Deserialiter, f.E. look here: http://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base With a bit reflection magic, you could check all properties with a valid setter and map it to the JSON-Data by Naming convention. – Matthias Müller Jun 22 '15 at 10:18
  • 1
    Are you wanting to just deserialize to some kind of anonymous type so you can read the data without caring what sort of an object it is? If so the newtonsoft library will let you do this. – Chris Jun 22 '15 at 10:39
  • This question isn't really about deserialisation per-sae it's more about dynamically adding properties to a C# class based on dynamic input data. – dougajmcdonald Jun 22 '15 at 11:37

3 Answers3

1

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)

Community
  • 1
  • 1
Palanikumar
  • 6,940
  • 4
  • 40
  • 51
0

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);
        ;
    }
}
}
Stanislav Berkov
  • 5,929
  • 2
  • 30
  • 36
0

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