JSON.NET Converting class with custom data types

I'm using JSON.NET to try and convert a type of Bar to JSON.

public class Foo {
    String A;
    String B;
    Int32 C;
    DateTime D;
}

public class Bar {
    String E;
    String F;
    String G;
    Foo H;
}

And I'm using this to convert a Bar to JSON.

public String ConvertBar(Bar _bar) {
    String Result = JsonConvert.SerializeObject<Bar>(_bar);
    return Result;
}

Something like this should be output:

{
  "E": "Another Value",
  "F": "Flamingos",
  "G": "Another Another Value",
  "H": [
    {
      "A": "Some Value",
      "B": "Some Other Value",
      "C": 42,
      "D": "2000-01-013T00:00:00Z"
    }
  ]
}

Whatever I do, the output of ConvertBar() is always null. So how are you supposed to convert Bar into JSON while retaining the values of Foo? I've heard you have to create a converter but I have no experience in those.

1 answer

  • answered 2018-07-11 04:32 dotnetstep

    Either you can convert your field to property or Field decorated with [JsonProperty]

     public class Foo
        {
            [JsonProperty]
            String A;
            [JsonProperty]
            String B;
            [JsonProperty]
            Int32 C;
            [JsonProperty]
            DateTime D;
        }
    
        public class Bar
        {
            public Bar()
            {
                H = new Foo();
            }
            [JsonProperty]
            String G;
            [JsonProperty]
            Foo H;
            public String E { get; set; }
            public String F { get; set; }
        }
    

    After using your ConvertBar function I get following output.

    {"G":null,"H":{"A":null,"B":null,"C":0,"D":"0001-01-01T00:00:00"},"E":null,"F":null}