简体   繁体   中英

Reading json data from external api using C#

I am trying to read json data that is coming from a api, and I just want to read objects from this data..

 string id_url = "http://abc/some_id";

 WebRequest requst = WebRequest.Create(id_url);
 requst.Method = "GET";
 requst.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("user:password"));

 HttpWebResponse response = requst.GetResponse() as HttpWebResponse;

 var encod = ASCIIEncoding.ASCII;

 using (var readchat = new System.IO.StreamReader(response.GetResponseStream(), encod))
 {
     string chatresult = readchat.ReadToEnd();

     var json = JObject.Parse(chatresult);
 }

and I am getting json as:

{
      "comment": null,
      "triggered_response": true,
      "rating": null,
      "visitor": {
        "phone": "",
        "name": "abc"
      },

      "history": [
        {
          "name": "Visitor 7949",
          "department_name": null,
          "type": "chat.memberjoin",
          "department_id": null
        },
        {
          "name": "fdef",
          "sender_type": "Trigger",
          "msg": "Welcome back! How may I help you today?",
          "type": "chat.msg"        
        },
        {
          "name": "use",
          "sender_type": "Trigger",
          "msg": "good morning",
          "type": "chat.msg"        
        }
      ]
}

I have to read only "msg" tag data from json using C#. I have tried this:

string data = json["history"].ToString();

by using above am getting the data from "history" tag but how will am able to get text from history[array].msg as we do using javascript ajax.

You can use JsonConvert with dynamic object JsonConvert.DeserializeObject<dynamic>(data)

Sample code:

string data = " {\"comment\": null,   \"triggered_response\": true,   \"rating\": null,   \"visitor\": {    \"phone\": \"\",    \"name\": \"abc\"   },   \"history\": [    {     \"name\": \"Visitor 7949\",     \"department_name\": null,     \"type\": \"chat.memberjoin\",     \"department_id\": null    },    {     \"name\": \"fdef\",     \"sender_type\": \"Trigger\",     \"msg\": \"Welcome back! How may I help you today?\",     \"type\": \"chat.msg\"        },{     \"name\": \"use\",     \"sender_type\": \"Trigger\",     \"msg\": \"good morning\",     \"type\": \"chat.msg\"        }   ]  }";

var dynamicobject = JsonConvert.DeserializeObject<dynamic>(data);

var historyname = dynamicobject.history[0].name.ToString();
  //data structure for mapping
public class History {
  public string name { get; set; }
  public string sender_type { get; set; }
  public string msg { get; set; }
  public string type { get; set; }
}

public class Visitor {
  public string Phone { get; set; }
  public string Name { get; set; }
}


public class ObjectThatContainsHistory {
  public string Comment { get; set; }
  public bool Triggered_Response { get; set; }
  public string Rating { get; set; }
  public Visitor Visitor { get; set; }

  public List<History> History { get; set; }
}

  var jsonString =
    @"{
        ""comment"": null,
        ""triggered_response"": true,
        ""rating"": null,
        ""visitor"": {
          ""phone"": """",
          ""name"": ""abc""
        },

        ""history"": [
          {
            ""name"": ""Visitor 7949"",
            ""department_name"": null,
            ""type"": ""chat.memberjoin"",
            ""department_id"": null
          },
          {
            ""name"": ""fdef"",
            ""sender_type"": ""Trigger"",
            ""msg"": ""Welcome back! How may I help you today?"",
            ""type"": ""chat.msg""        
          },
          {
            ""name"": ""use"",
            ""sender_type"": ""Trigger"",
            ""msg"": ""good morning"",
            ""type"": ""chat.msg""        
          }
        ]
    }";

  ObjectThatContainsHistory objectThatContainsHistory = JsonConvert.DeserializeObject<ObjectThatContainsHistory>(jsonString);

  var messages = objectThatContainsHistory.History
    .Select(x => x.msg)
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM