2

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.

4
  • You should make your properties public and also have a parameterless constructor in both the classes Commented Jul 11, 2018 at 3:54
  • Those aren't really the complete classes. They're just the bare bones of what the actual classes on my code contain. I already have the properties public and I already have constructors in place. I'm really just stumped on converting it. Commented Jul 11, 2018 at 3:58
  • Now I see that nowhere you are serializing the bar object, you are serializing MessageJSON property Commented Jul 11, 2018 at 3:59
  • Whoops. I forgot to edit that out. It was a fragment of my actual code. I just copied it to be quicker. Fixed it now. Commented Jul 11, 2018 at 4:02

1 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.