2017-03-01 64 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; } 
}