2012-02-04 3 views
2

я есть JSon строку как:Как получить значения в JSON в C#?

{ 
     "data": [ 
      { 
      "id": "100000045402409_310121622373595", 
      "from": { 
       "name": "Ritesh Ranjan", 
       "id": "100000045402409" 
      }, 
      "message": "greatttttttttttttt ab jaooooooooo", 
      "picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQAGY5rsr5AeM5PI&w=90&h=90&url=http\u00253A\u00252F\u00252Fwww.ndtv.com\u00252Fnews\u00252Fimages\u00252Ftopstory_thumbnail\u00252FChidambaram_2G_120.jpg", 
      "link": "http://www.ndtv.com/article/india/2g-scam-chidambaram-verdict-expected-shortly-huge-implications-for-govt-173168", 
      "name": "2G scam: Chidambaram verdict expected shortly, huge implications for govt", 
      "caption": "www.ndtv.com", 
      "description": "A Delhi court handling the 2G spectrum allocation scam trial is likely to decide today whether Union Home Minister P Chidambaram should be made a co-accused in the case for allegedly allowing former Telecom Minister A Raja to gift mobile network licenses and scarce second-generation or 2G spectrum a...", 
      "icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif", 
      "type": "link", 
      "application": { 
       "name": "Links", 
       "id": "2309869772" 
      }, 
      "created_time": "2012-02-04T11:02:22+0000", 
      "updated_time": "2012-02-04T11:02:22+0000" 
      }, 
      { 
      "id": "100003303253347_132959650157476", 
      "from": { 
       "name": "Suman Dey", 
       "id": "100003303253347" 
      }, 
      "message": "Check out this article I was reading on biNu. 2G verdict: Chidambaram off the hook, government exhales", 
      "type": "status", 
      "application": { 
       "name": "biNu", 
       "canvas_name": "binuapp", 
       "namespace": "binuapp", 
       "id": "378628085054" 
      }, 
      "created_time": "2012-02-04T10:54:19+0000", 
      "updated_time": "2012-02-04T10:54:19+0000" 
      }, 
..... 
//Continued... 

Теперь я хочу, чтобы разобрать его с помощью C#

я использовал:

WebClient client = new WebClient(); 
       string Json = client.DownloadString("https://graph.facebook.com/search?q=2g+verdict+Chidambaram&type=post"); 
       System.IO.StreamWriter SW = new System.IO.StreamWriter(JsonDestFile); 
       SW.WriteLine(Json); 

       System.IO.StreamWriter SW1 = new System.IO.StreamWriter(ValuesDestFile); 

       JObject o = JObject.Parse(Json); 
var postTitles = from p in o["data"].Children()["from"] 
          select p["name"].Values<string>(); 

         foreach (var item in postTitles) 
         { 
          SW1.WriteLine(item); 
         } 
       SW1.WriteLine(name); 

Но я не могу получить любые name значения на всех ,

Его дает мне сообщение об ошибке: Cannot access child value on Newtonsoft.Json.Linq.JValue.

Пожалуйста, предложите мне, как я могу разобрать выше JSON для значений id, name, id (from one) , message

ответ

4

Я получил это работаю ...

var postTitles = from p in JO["data"].Children() 
          select new 
          { 
           Names = (string)p["from"]["name"], 
           Msg = (string)p["message"], 
          }; 

Используя этот LINQ я могу получить доступ к необходимым данным.

1

вам нужно deseriralise строку JSON, как показано ниже

public static T Deserialise<T>(string json) 
{ 
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) 
    { 
     var serialiser = new DataContractJsonSerializer(typeof(T)); 
     return (T)serialiser.ReadObject(ms); 
    } 
} 

Вернуться тип у вас класс

public class MyData 
{ 
    public string id { get; set;} 
    public string name{ get; set;} 
    public string message{ get; set;} 
} 

вы можете проверить полную информацию: Parse JSON in C#

2

Я не использовал LINQ to JSON API, но если вы не настаиваете на его использовании, вы можете просто создать класс, который моделирует данные в вашей полезной нагрузке JSON, а затем использовать следующий метод:

Newtonsoft.Json.JsonConvert.DeserializeObject<YourDataModelClass>() 
0

Это также будет работать

JObject hh = JObject.Parse(jsonstring); 
string name = (string)hh["Name"]; 
Смежные вопросы