简体   繁体   中英

Creating C# object from JSON data retrieved from HttpWebResponse

First, I'm absolutely terrible at programming. I always have been. The simplest, most trivial things that any other human being in the world seems to just 'get' tend to trip me up and lead me to uncontrollable rage quitting. That out of the way, sorry for the stupid question. :P

I'm basically trying to take some JSON values returned from an HttpWebResponse and put them into C# object. The JSON values pertain to a list of clients. I want to be able to turn them into C# objects that I can then use throughout my program (ex client.name, client.phone_number, etc...).

The code below is more of a proof of concept than final code. I login to a WordPress site and then pull JSON data from a page on the site. I'm able to retrieve and see the returned JSON data (as one long jumbled string). I just can't figure out how to extract from that string the particular values I need to create 'client' objects from them.

        string loginUri = "URL TO WORDPRESS LOGIN";
        string username = entryUsername;
        string password = entryPassword;
        string reqString = "log=" + username + "&pwd=" + password;
        byte[] requestData = Encoding.UTF8.GetBytes(reqString);

        CookieContainer loginCookie = new CookieContainer();
        var request = (HttpWebRequest)WebRequest.Create(loginUri);
        request.Proxy = null;
        request.AllowAutoRedirect = false;
        request.CookieContainer = loginCookie;
        request.Method = "POST";

        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = requestData.Length;
        using (Stream s = request.GetRequestStream())
        {
            s.Write(requestData, 0, requestData.Length);

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                foreach (Cookie currentCookie in response.Cookies)
                {
                    Console.WriteLine(currentCookie.Name + " = " + currentCookie.Value); // debug purposes
                    request.CookieContainer.Add(currentCookie);
                }
            }
        }

        // Debug purposes
        Console.WriteLine("{0} cookie(s) have been downloaded, Jim.", loginCookie.Count.ToString());

        string clientListURI = "PAGE CONTAINING JSON";
        HttpWebRequest clientListRequest = (HttpWebRequest)WebRequest.Create(clientListURI);
        clientListRequest.Proxy = null;
        clientListRequest.Method = "POST";
        clientListRequest.ContentLength = 0;
        clientListRequest.ContentType = "application/json";
        clientListRequest.CookieContainer = loginCookie;
        using (HttpWebResponse clientListResponse = (HttpWebResponse)clientListRequest.GetResponse())
        using (Stream resSteam = clientListResponse.GetResponseStream())
        {
            JsonValue jsonDoc = JsonObject.Load(resSteam);
            Console.WriteLine("Response: {0}", jsonDoc.ToString ());
        }          

Sample Json:

{
    id: "26",
    owner: "7",
    owner_name: "Bradford Kolumbic",
    Status: "0",
    status_name: "None",
    Milestone: "0",
    milestone_name: "None",
    small_text_1: "Ghost Buster Solutions",
    small_text_8: "Business",
    small_text_7: "(858) 123-5432",
    small_text_2: "123 ABC Street",
    small_text_4: "Escondido",
    small_text_5: "California",
    small_text_6: "92027"
}

I created a class, Client, that can be used to store each client profile from the returned JSON.

public class Client
{
    public string id { get; set; }
    public string owner { get; set; }
    public string owner_name { get; set; }
    public string Status { get; set; }
    public string status_name { get; set; }
    public string Milestone { get; set; }
    public string milestone_name { get; set; }
    public string small_text_1 { get; set; }
    public string small_text_8 { get; set; }
    public string small_text_7 { get; set; }
    public string small_text_2 { get; set; }
    public string small_text_4 { get; set; }
    public string small_text_5 { get; set; }
    public string small_text_6 { get; set; }
}

I've tried all sorts of different ways but nothing seems to work right for me. I'm sure I'm missing something ridiculously obvious.

The last thing I've tried is:

var JsonClientList = JsonConvert.DeserializeObject<List<Client>>(jsonDoc); 

It errors out though with "Unable to cast object of type 'System.Json.JsonObject' to type 'System.Json.JsonPrimitive'."

Any help for this young fool would be greatly appreciated. Thank you for your time.

this works for me

var json =@"
{
    id: ""26"",
    owner: ""7"",
    owner_name: ""Bradford Kolumbic"",
    Status: ""0"",
    status_name: ""None"",
    Milestone: ""0"",
    milestone_name: ""None"",
    small_text_1: ""Ghost Buster Solutions"",
    small_text_8: ""Business"",
    small_text_7: ""(858) 123-5432"",
    small_text_2: ""123 ABC Street"",
    small_text_4: ""Escondido"",
    small_text_5: ""California"",
    small_text_6: ""92027""
}";

var c = JsonConvert.DeserializeObject<Client>(json); 

If the sample you gave is the whole JSON object, then it is not a collection of clients ( List<Client> ) but only a Client

I would suggest you go here: http://json2csharp.com/ and input your JSON. They will instantly create C# classes for you.

Then I would add the NewtonSoft.Json nuget-package to my project. And then finally call something like

JsonConvert.Deserialize<List<Client>>(jsonDoc);

This is the code that I'm using. To do an HTTPRequest:

 public static string DoJsonRequest(string url, MemoryStream content)
        {

            byte[] dataByte = content.ToArray();

            //create http web request obj
            WebRequest postRequest = WebRequest.Create(url);
            //Method type
            postRequest.Method = "POST";
            // Data type - message body coming in xml
            postRequest.ContentType = "application/json; charset=utf-8";
            //Content length of message body
            postRequest.ContentLength = dataByte.Length;

            // Get the request stream
            using (Stream postStream = postRequest.GetRequestStream())
            {
                // Write the data bytes in the request stream
                postStream.Write(dataByte, 0, dataByte.Length);
                //Get response from server
                using (HttpWebResponse postResponse = (HttpWebResponse)postRequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(postResponse.GetResponseStream()))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }



        public static string GetJsonFromObject<TObject>(TObject obj, IEnumerable<Type> types)
        {
            using (var stream = new MemoryStream())
            {
                var jsSerializer = new DataContractJsonSerializer(typeof(TObject), types);

                jsSerializer.WriteObject(stream, obj);
                stream.Position = 0;

                using (StreamReader reader = new StreamReader(stream))
                {
                    string json = reader.ReadToEnd();
                    return json;
                }
            }
        }



public static TObject GetObjectFromJson<TObject>(string json, IEnumerable<Type> types)
{

    using (MemoryStream stream = new MemoryStream())
    {
        using (StreamWriter writer = new StreamWriter(stream))
        {
            writer.Write(json);
            writer.Flush();
            stream.Position = 0;

            var jsSerializer = new DataContractJsonSerializer(typeof(TObject), types);

            TObject obj = (TObject)jsSerializer.ReadObject(stream);

            return obj;
        }
    }
}

You can see I'm using Generics.

For call the Method and do the request to an RESTFull Service.

 using (MemoryStream stream = new MemoryStream())
                {
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        writer.Write(json);
                        writer.Flush();
                        stream.Position = 0;

                        string response = HttpHelper.DoJsonRequest("https://localhost:44300/RestFull.svc/Execute", stream);

                        response = response.Remove(0, 1);
                        response = response.Remove(response.Length - 1, 1);
                        response = response.Replace("\\\"", "\"");
                        Data data = HttpHelper.GetObjectFromJson<Data>(response, Types);

                    }
                }

Where Json = "\\"" + HttpHelper.GetJsonFromObject<Data>(request, Types).Replace("\\"", "\\\\\\"") + "\\"";

Oh Another way to do this if you are using Vs 2013 is to get the JSON on Clipboard. Create a new file in VS then Paste Special. Poof it is all set.

Mark

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