从HttpWebResponse检索的JSON数据创建C#对象

时间:2015-03-25 23:44:57

标签: c# json xamarin

首先,我在编程方面非常糟糕。我一直都是。世界上任何其他人似乎只是“得到”的最简单,最微不足道的事情往往会惹恼我,导致我无法控制的愤怒退出。那个偏僻,抱歉这个愚蠢的问题。 :P

我基本上是尝试从HttpWebResponse返回一些JSON值并将它们放入C#对象。 JSON值与客户端列表有关。我希望能够将它们转换为C#对象,然后我可以在整个程序中使用它(e.x. client.name,client.phone_number等...)。

下面的代码比最终代码更像是一个概念验证。我登录到WordPress网站,然后从网站上的页面中提取JSON数据。我能够检索并查看返回的JSON数据(作为一个冗长的混乱字符串)。我只是无法弄清楚如何从该字符串中提取我需要从中创建“客户”对象所需的特定值。

        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 ());
        }          

示例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"
}

我创建了一个类Client,可以用来存储返回的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; }
}

我尝试过各种不同的方法,但似乎没有什么能适合我。我敢肯定我错过了一些非常明显的东西。

我尝试的最后一件事是:

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

虽然“无法将类型为'System.Json.JsonObject'的对象强制转换为'System.Json.JsonPrimitive',但它出错了。”

对这位年轻傻瓜的任何帮助都将不胜感激。谢谢你的时间。

4 个答案:

答案 0 :(得分:0)

这对我有用

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); 

如果您提供的示例是整个JSON对象,那么它不是客户端集合(List<Client>),而只是Client

答案 1 :(得分:0)

我建议你到这里:http://json2csharp.com/并输入你的JSON。他们会立即为您创建C#类。

然后我会将NewtonSoft.Json nuget-package添加到我的项目中。然后最后打电话给

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

答案 2 :(得分:0)

这是我正在使用的代码。 要执行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;
        }
    }
}

你可以看到我正在使用Generics。

用于调用Method并对RESTFull服务执行请求。

 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);

                    }
                }

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

答案 3 :(得分:-1)

哦如果您使用Vs 2013,另一种方法是在剪贴板上获取JSON。在VS中创建一个新文件,然后选择Paste Special。噗就是这样。

标记