简体   繁体   中英

C# JSON to object (or array)

I'm trying to get pos 'x' and 'y' from JSON file (a part of STL file with coordinates of polygons) to array or object using newtonsoft package but unsuccessfully.

That looks my original file and converted by JSON online

I've read this but gives me a lots of errors.

Would you give me some tips or example ?

Thanks in advance

  try 
  {
      using (StreamReader reader = new StreamReader("test.json"))
      {
          json = reader.ReadToEnd();
          List<vertex> items = JsonConvert.DeserializeObject<List<vertex>>(json);
      }

      dynamic array = JsonConvert.DeserializeObject(json);
             foreach (var vert in array)
             {
                 Console.WriteLine("{0} {1}",  vert.x, vert.y);
             }
  }
  catch(Exception ex)
  {
      MessageBox.Show(ex.ToString());
  } 

  public class vertex
  {
      public double x,y;
  }

The file for deserializing into the class you're using should be in the format

[{ "x" : 1.3214, "y" : 0.13241},{ "x" : 3.4324, "y" : 0.324}]

For deserializing the file you have, it shoud have a class as:

 public class Coordinates {
   public decimal Z { get; set; }
   public List<Point> Polygons { get; set; }
 }
 public class Point{
  public List<vertex> points { get; set; } 
 }
 public class vertex{
   public List<decimal> Vertices { get; set; }
   public decimal x { get {return Vertices?[0]} }
   public decimal y { get {return Vertices?[1]} }
 }

This worked perfectly ;)

public class Polygonn
    {
        public List<List<double>> points { get; set; }
        public string type { get; set; }
    }

    public class RootObject
    {
        public double z { get; set; }
        public List<Polygonn> polygons { get; set; }
    }


string data = System.IO.File.ReadAllText("backup.json");
 RootObject json = JsonConvert.DeserializeObject<RootObject>(data);
 json.polygons[polygon].points[0].ElementAt(0)

Thanks for everyone! Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM