6

I am getting a string with json objects from an external webapi. I have a code that gets the objects into a ExpandoObject list, but there must be another solution without using dynamic object.

Here is the code:

System.Net.HttpWebRequest request = 

(System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://example.com/api/users.json");
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Headers["Authorization"] = "API key="+somekey;
// Ignore Certificate validation failures (aka untrusted certificate + certificate chains)
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
//response from the api
string responseFromServer = reader.ReadToEnd();
//serialize the data
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
System.Collections.IList users = (System.Collections.IList)((IDictionary<string, object>)((IDictionary<string, object>)jss.DeserializeObject(responseFromServer))["data"])["users"];

List<System.Dynamic.ExpandoObject> api_users = new List<System.Dynamic.ExpandoObject>();
//putting the expandable objects in list
foreach (var u in users)
{
    var user = ((Dictionary<string, object>)((IDictionary<string, object>)u)["User"]);
    dynamic data = new System.Dynamic.ExpandoObject();
    //putting the user attributes into dynamic object
    foreach (var prop in user)
    {
        ((IDictionary<String, Object>)data).Add(prop.Key, prop.Value);
    }
    api_users.Add(data);
}

Here is a sample of the json string:

"data": {
    "users": [
      {
        "User": {
          "user_id": "6741",
          "email": "[email protected]",
          "first_name": "Mark",
          "last_name": "Plas",
          "street_address": "",
          "post_code": "",
          "city": ""
        },
        "CreatedBy": {
          "id": null,
          "name": null
        },
        "ModifiedBy": {
          "id": null,
          "name": null
        }
      },...(can have more users here)

1 Answer 1

2

You can use one of the many C# JSON parsers to do this. I personally prefer JSON.Net (which you can install via NuGet). It can deserialize to both dynamic objects as well as to your own statically-typed classes.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't want to use external libraries, if that's possible

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.