如何在c# . net中解析Json

本文关键字:Json net | 更新日期: 2023-09-27 17:49:14

我在c#工作。我想在应用程序中解析JSON。但不知道如何解析Json。我在谷歌上搜索了很多,但是找不到足够的资料。我的JSOn是…

[{"id":"267","name":"Macmillan Nursing Service","telephone":"01595 743347",
"addr1":"Gilbert Bain Hospital","town":"Shetland","postcode":"ZE1 0TB",
"lat":"60.1505513","lng":"-1.1546642","distance":"3278.42778426762"},
{"id":"355","name":"Orkney Macmillan House","telephone":"01856 888249",
"addr1":"Balfour Hosptial","town":"","postcode":"KW15 1BH","lat":"58.9767143",
"lng":"-2.9649377","distance":"3421.52913012431"},
{"id":"57",
"name":"Community Macmillan Nurse","telephone":"01779 482568",
"addr1":"Peterhead Health    Centre","town":"Peterhead",
"postcode":"AB422XA","lat":"57.5034159","lng":"-1.7939854",
"distance":"3425.64696427705"},
{"id":"287","name":"Macmillan
Service","telephone":"01955 880397","addr1":"Caithness
General Hospital","town":"Wick","postcode":"KW1 5NS","lat":"58.4415",
"lng":"-3.09651","distance":"3452.34795736445"},
{"id":"288","name":"Macmillan Service",
"telephone":"01888 564015","addr1":"The Health Centre","town":"Banff","postcode":"AB45  
1HY","lat":"57.6686963","lng":"-2.5256111","distance":"3457.45181828202"}]

我在这个工作中卡住了,请帮助我。

任何帮助都太好了。或者一些关于如何解析Json的提示也足够了。

如何在c# . net中解析Json

使用一个出色的Json.net库

特性
Flexible JSON serializer for converting between .NET objects and JSON
LINQ to JSON for manually reading and writing JSON
High performance, faster than .NET's built-in JSON serializers
Write indented, easy to read JSON
Convert JSON to and from XML
Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone

序列化器是一个很好的选择,当你正在读取JSON或写映射到。net类。

LINQ to JSON适用于您只感兴趣的情况从JSON中获取值,你没有一个类来序列化或反序列化到,或者JSON与您的类和完全不同你需要手动读取和写入你的对象。

似乎需要将JSON字符串反序列化为对象。你可以创建一个代表对象的类,然后将json反序列化到它。

之类的
class Information
{
   int id;
   string name;
   string telephone;
   // etc
}

然后像这样反序列化

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
// Using List<T> as the JSON is organised like an array
List<Information> info = (List<Information >)json_serializer.DeserializeObject(JSONFeed);

其中JSONFeed是您的json字符串从网站。

有关更深入的方法,请参阅-代码项目教程