C#Json.Net读取数据

时间:2017-03-01 09:39:37

标签: c# json

虽然我已经弄清楚如何用 Newtonsoft 读取JSON文件,但不知道我如何阅读这些点。我想阅读所有X,Y点。什么是最好的方法呢?我有整个JSON文件"阅读"我现在如何获得个人观点?

这是JSON文件的一个小摘录:

{
  "Points": [
    {
      "X": -3.05154,
      "Y": 4.09
    },
    {
      "X": -3.05154,
      "Y": 3.977
    }
  ],
  "Rectangles": [
    {
      "XMin": -3.08154,
      "XMax": 3.08154,
      "YMin": -4.5335,
      "YMax": 4.5335
    }
  ]
}
JObject o1 = JObject.Parse(File.ReadAllText(@"C:\Users\user\Desktop\test.json"));
Koordinaten kor = new Koordinaten();
// read JSON directly from a file
using (StreamReader file = File.OpenText(@"C:\Users\user\Desktop\test.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
    JObject o2 = (JObject)JToken.ReadFrom(reader);
}

2 个答案:

答案 0 :(得分:2)

让我们分两部分回答:

<强> 1。创建JSON类(模型)

如果您使用的是Visual Studio,这很容易:

  1. 创建新文件(类)
  2. 复制到剪贴板上面的JSON代码
  3. Visual Studio 中,转到“编辑” - &gt;粘贴特殊 - &gt;将JSON粘贴为类
  4. 这将生成您可以用来反序列化对象的类:

    public class Rootobject
    {
        public Point[] Points { get; set; }
        public Rectangle[] Rectangles { get; set; }
    }
    
    public class Point
    {
        public float X { get; set; }
        public float Y { get; set; }
    }
    
    public class Rectangle
    {
        public float XMin { get; set; }
        public float XMax { get; set; }
        public float YMin { get; set; }
        public float YMax { get; set; }
    }
    

    <强> 2。将JSON反序列化为类

    string allJson = File.ReadAllText(@"C:\Users\user\Desktop\test.json");
    Rootobject obj = JsonConvert.DeserializeObject<Rootobject>(allJson);
    
    Console.WriteLine($"X: {obj.Points[0].X}\tY:{obj.Points[0].Y}");
    

答案 1 :(得分:1)

一种简单的方法是创建一个与JSON数据结构相匹配的类。可以找到一个示例here

using System;
using Newtonsoft.Json;

public class Program
{
    static string textdata = @"{
  ""Points"": [
    {
      ""X"": -3.05154,
      ""Y"": 4.09
    },
    {
      ""X"": -3.05154,
      ""Y"": 3.977
    }
  ],
  ""Rectangles"": [
    {
      ""XMin"": -3.08154,
      ""XMax"": 3.08154,
      ""YMin"": -4.5335,
      ""YMax"": 4.5335
    }
  ]
}";

    public static void Main()
    {
        var data = JsonConvert.DeserializeObject<Data>( textdata );
        Console.WriteLine( "Found {0} points", data.Points.Length );
        Console.WriteLine( "With first point being X = {0} and Y = {0}", data.Points[0].X, data.Points[0].Y);
    }
}

public class Data {
    public Point[] Points { get; set; }
}

public class Point {
    public decimal X { get; set; }
    public decimal Y { get; set; }
}