2017-03-01 67 views
0

虽然我已经想出了如何使用Newtonsoft来读取JSON文件,但并不知道如何阅读这些要点。我想阅读所有X,Y点。什么是最好的方法来做到这一点?我有整个JSON文件“读”,我现在如何得到个人点?C#Json.Net读取数据

这是从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); 
} 
+4

您可以尝试将JSON反序列化为“真实”类而不是JObject – Icepickle

回答

2

我们分了答案2个部分:

1.创建JSON类(模型)

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

  1. 创建新文件(类)
  2. 复制到剪贴板上述
  3. 你的JSON代码在Visual Studio中去编辑 - >选择性粘贴 - >粘贴JSON作为类

这将生成您可以用来反序列化对象的类:

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

一个简单的方法来做到这将是创建一个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; } 
}