GabelUndMesser GabelUndMesser -4 years ago 134
JSON Question

C# Json.Net read data

Although I have figured out how I can read the JSON file with Newtonsoft, but not how I can read the points. I would like to read all X, Y points. Whats the best way to do this? I have the whole JSON file "read" and how do I get now the individual points out?

This is a small extract from the JSON file:

{
"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);
}

Answer Source

Let's split answer in 2 parts:

1. Create JSON class (model)

If You are using Visual Studio, this is easy:

  1. Create new file (class)
  2. Copy to clipboard Your JSON code above
  3. In Visual Studio go to Edit -> Paste special -> Paste JSON as Classes

This will generate You the class(es), which You can use to deserialize object:

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. Deserialize JSON into class

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}");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download