0

I have this case:

public class X
{
   public A a;
   public B b;

   public X () 
   {
      this.a = new A();
      this.b = new B();
   }
}

public class A
{
   public int c;
   public int d;
}

public class B
{
   public int e;
   public int f;
}

In my C# code I get an instance of X and I set all the properties of class A and B, and I serialize the resulting object with the JavaScriptSerializer. Since here, no problem. I have this JSON string:

{
  "a": {
     "c": 1,
     "d": 1
  },
  "b": {
     "e": 1,
     "f": 1
  }
}

Now, after this primary complete serialization, I want to create an istance of X setting, for example, only properties of the class A, and not class B, because I need a JSON string like this:

{
  "a": {
     "c": 1,
     "d": 1
  }
}

How do I do that? If I get an instance of X, properties of class B will have default values. I tried to condition the X constructor with a boolean value, but in the JSON string i see NULL values for the B properties.

How can I resolve this problem?

Thank you all, Alessio

bichito
  • 1,406
  • 2
  • 19
  • 23
  • Can you check out this question? http://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net It's using Newtonsoft.Json package but the idea can be applied to default java script serializer too. – Tequilalime Apr 24 '17 at 13:53
  • 1
    Possible duplicate of [How to ignore a property in class if null, using json.net](http://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net) – vipersassassin Apr 24 '17 at 14:00

0 Answers0