简体   繁体   English

C#JSON到对象(或数组)

[英]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. 我正在尝试使用newtonsoft包从JSON文件(具有多边形坐标的STL文件的一部分)中将pos'x'和'y'转换为数组或对象,但未成功。

That looks my original file and converted by JSON online 看起来像我的原始文件,并通过JSON在线转换

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 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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