skip to Main Content

I have been trying to display contents of a json file in a textbox for the past 6 hours and got nowhere.
here’s the c# code

        private thruster Getthruster()
        {
            string text = File.ReadAllText(@"./thrusters.json");
            List<thruster> test = JsonConvert.DeserializeObject<List<thruster>>(text);
        
            textBox1.Text = text;
        
            foreach (var item in test)
            {
                textBox1.Text = item.type;
            }
            return Getthruster();
        }


        public class thruster
        {
            public string id { get; set; }
            public string type { get; set; }
            public string placement { get; set; }
        }
{
  "thruster": [
    {
      "id": 1,
      "type": "tunnel",
      "placement": "bow"
    },
    {
      "id": 2,
      "type": "tunnel",
      "placement": "bow"
    },
    {
      "id": 3,
      "type": "azimuth",
      "placement": "bow"
    },
    {
      "id": 5,
      "type": "azimuth",
      "placement": "stern"
    },
    {
      "id": 5,
      "type": "tunnel",
      "placement": "stern"
    },
    {
      "id": 6,
      "type": "azimuth_propulsion"
    },
    {
      "id": 7,
      "type": "azimuth_propulsion"
    }
  ]
}

2

Answers


  1. To start, you are running into a StackOverflowException since you are calling the same method (Getthruster()) inside the same method without any exit condition.

    After this, your json file seems to be incorrect. You have there a Dictionary<string,thruster[]> and not a thruster[] (Or List).

    Your json for a thruster[] or List<thruster> should be something like:

    [
      {
        "id": "1",
        "type": "t",
        "placement": "top"
      },
      {
        "id": "2",
        "type": "t",
        "placement": "top"
      }
    ]
    
    Login or Signup to reply.
  2. you have an object inside of a json string, but you try to serialize it as it is an array. You can use this code that deserializes an array inside of your json

     List<thruster> test = JObject.Parse(text)["thruster"].ToObject<List<thruster>>();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search