从Json字符串

时间:2016-06-09 05:33:33

标签: c# json

我有JSON数据:

{"title":"",
"query":"pakistan",
"for":"daily",
"method":3,
"prayer_method_name":"University Of Islamic Sciences,
 Karachi (Hanafi)",
"daylight":"0",
"timezone":"5",
"map_image":"http:\/\/maps.google.com\/maps\/api\/staticmap?center=30.375321,69.345116&sensor=false&zoom=13&size=300x300",
"sealevel":"1376",
"today_weather":{"pressure":null,"temperature":null},
"link":"http:\/\/muslimsalat.com\/pakistan",
"qibla_direction":"258.33",
"latitude":"30.375321",
"longitude":"69.345116",
"address":"","city":"",
"state":"",
"postal_code":"",
"country":"Pakistan",
"country_code":"PK",
"items":[{"date_for":"2016-6-9","fajr":"3:43 am","shurooq":"5:09 am","dhuhr":"12:21 pm","asr":"5:15 pm","maghrib":"7:34 pm","isha":"9:00 pm"}],
"status_valid":1,
"status_code":1,
"status_description":"Success."}

我只需要来自JSON的特定数据,例如,

  “fajr”:“3:43 am”,“shurooq”:“上午5:09”,“dhuhr”:“12:21 pm”,   “asr”:“5:15 pm”,“maghrib”:“7:34 pm”,“isha”:“9:00

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:0)

您必须将JSON解析为对象。为此,您可以使用JSON.NET

以下是有关如何将JSON字符串解析为动态对象的示例:

string source = "YOUR JSON";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.fajr);
Console.WriteLine(data.shurooq);
Console.WriteLine(data.dhuhr);
etc...

答案 1 :(得分:0)

您可以使用JSON序列化程序,例如http://www.newtonsoft.com/json

然后您将拥有以下模型:

public class Item
{
    public string date_for { get; set; }
    public string fajr { get; set; }
    public string shurooq { get; set; }
    public string dhuhr { get; set; }
    public string asr { get; set; }
    public string maghrib { get; set; }
    public string isha { get; set; }
}

public class ItemContainer
{
    public List<Item> Items { get; set; }
}

并使用json.net,您可以检索值

var data = JsonConvert.DeserializeObject<ItemContainer>(your json);
if (data.Items.Count > 0)
{
   var fajr = data.Items[0].fajr;
   var dhuhr = data.Items[0].dhuhr; 
   ...
}

答案 2 :(得分:0)

假设您的json存储在MyData变量中:

所以取值是:

  • MyData.items =&gt;返回对象
  • MyData.items.fajr =&gt;返回字符串
  • MyData.items.shurooq =&gt;返回字符串
  • MyData.items.dhuhr =&gt;返回字符串
  • MyData.items.asr =&gt;返回字符串
  • MyData.items.maghrib =&gt;返回字符串
  • MyData.items.isha =&gt;返回字符串

使用newtonsoft.json:

var shalaSchedule = JsonConvert.DeserializeObject<Dictionary<string, object>>(MyData);

这样您就可以从shalaSchedule["items"][0]["magrib"].toString();

中读取数据

答案 3 :(得分:0)

您可以创建一个包含json keys等属性的类。然后您可以轻松地将其反序列化,如下所示。

class TemplateResponse
{
    public String multicast_id;
    public String success;
    public String failure;
    public String canonical_ids;
    public Result[] results;

    public class Result
    {
        public String message_id;
        public String registration_id;
        public String error;
    };
}

Json String:

"\"multicast_id\":7400896764380883211,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1351777805148960%39895cf0f9fd7ecd\"}]}"

然后反序列化,如下面的代码段:

TemplateResponse result = new JavaScriptSerializer().Deserialize<TemplateResponse>(json);