0

I'm sure I am missing something very obvious, and I've read different threads (like this one, this and also this, just to name the last ones) but I still cannot find the answer...

Here are my classes:

using System;
using Newtonsoft.Json;

namespace WebAPIClient
{
  public class XWTournament
  {
    private string name;

    [JsonProperty("name")]
    public string Name { get => name; set => name = value; }
  }

  public class Root 
  {
    public XWTournament xwtournam { get => xwtournam; set => xwtournam = value; }
  }
}

And here I try to use them:

msg = "{\"tournament\": {\"Name\": \"Worlds 2014 Flight One\"}}";

Root root = JsonConvert.DeserializeObject<Root>(msg) ;
string pippo = root.xwtournam.Name;

But in this case I am receiving a stack overflow error...

What am I missing? How can I read the variables in the string?

Edit: thanks to the useful answers, I have corrected the code in this way

using System;
using Newtonsoft.Json;

namespace WebAPIClient
{
    public class XWTournament
    {
        //I've deleted the private variable
        public string Name { get; set; }

    }

    public class Root 
    {
        [JsonProperty("tournament")]
        public XWTournament xwtournam { get; set; }
    }
}
4
  • if you use my code you can solve your problem Commented Oct 24, 2017 at 16:52
  • You should not define getters/setters if there's no real functionality there. As you have it, { get; set; } would do exactly the same, and you wouldn't need private fields then. Commented Oct 24, 2017 at 18:03
  • @AmirHKH sorry, where is your code? Commented Oct 25, 2017 at 13:59
  • @jeff-skyrunner I posted it below, please use that and if you have any questions, i can explain it more Commented Oct 25, 2017 at 16:17

1 Answer 1

5

None of your classes have a property named tournament. Your JSON does. What does that suggest?

public class Root 
{
    public XWTournament tournament { get; set; }
}

You also don't need the infinite recursion in the setter as you wrote it. Try assigning to it: The getter and the setter both just call themselves. That's the cause of the stack overflow exception. You'd get one if you tried to set that property, too.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this helped me very much

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.