Как насчет JavaScriptSerializer ? Отличное интегрированное решение, которое можно расширить с помощью JavaScriptConverter s.
Демонстрация того, кем вы были после:
using System;
using System.Web.Script.Serialization;
using System.Text;
public class Stop
{
public String place { get; set; }
public Int32 KMs { get; set; }
}
public class Trip
{
public String from { get; set; }
public String to { get; set; }
public Stop[] stops { get; set; }
}
public class MyJSONObject
{
public Trip[] Trips { get; set; }
public override String ToString()
{
StringBuilder sb = new StringBuilder();
foreach (Trip trip in this.Trips)
{
sb.AppendFormat("Trip:\r\n");
sb.AppendFormat("\t To: {0}\r\n", trip.to);
sb.AppendFormat("\t From: {0}\r\n", trip.from);
sb.AppendFormat("\tStops:\r\n");
foreach (Stop stop in trip.stops)
{
sb.AppendFormat("\t\tPlace: {0}\r\n", stop.place);
sb.AppendFormat("\t\t KMs: {0}\r\n", stop.KMs);
}
sb.AppendLine();
}
return sb.ToString();
}
}
public class Test
{
public static void Main()
{
String example = "{\"Trips\":[{\"from\":\"here\",\"to\":\"there\",\"stops\":[{\"place\":\"middle1\",\"KMs\":37},{\"place\":\"middle2\",\"KMs\":54}]},{\"from\":\"there\",\"to\":\"here\",\"stops\":[{\"place\":\"middle2\",\"KMs\":37},{\"place\":\"middle1\",\"KMs\":54}]}]}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Parse the string to our custom object
MyJSONObject result = serializer.Deserialize<MyJSONObject>(example);
Console.WriteLine("Object deserialized:\r\n\r\n{0}\r\n\r\n", result);
// take our custom object and dump it in to a string
StringBuilder sb = new StringBuilder();
serializer.Serialize(result, sb);
Console.WriteLine("Object re-serialized:\r\n\r\n{0}\r\n\r\n", sb);
// check step
Console.WriteLine(example.Equals(sb.ToString()) ? "MATCH" : "NO match");
}
}
И вывод:
Object deserialized:
Trip:
To: there
From: here
Stops:
Place: middle1
KMs: 37
Place: middle2
KMs: 54
Trip:
To: here
From: there
Stops:
Place: middle2
KMs: 37
Place: middle1
KMs: 54
Object re-serialized:
{"Trips":[{"from":"here","to":"there","stops":[{"place":"middle1","KMs":37},{"pl
ace":"middle2","KMs":54}]},{"from":"there","to":"here","stops":[{"place":"middle
2","KMs":37},{"place":"middle1","KMs":54}]}]}
MATCH
Press any key to continue . . .