简体   繁体   English

JSON.NET从URL反序列化嵌套数据

[英]JSON.NET Deserialize Nested data from URL

I am trying to get JSON data via my localhost into command line. 我正在尝试通过本地主机将JSON数据输入命令行。 When I navigate the page via my web browser the following JSON is retuned: (I am using VS 2008) 当我通过Web浏览器浏览页面时,以下JSON被重新调整:(我使用的是VS 2008)

(http://LocalHost/example/00012/json.sp)

{"errors":[],
 "valid":true,
 "results":[{"address1":"2000 MAX1MAX2 ROAD","city":"Sunny City     ","state":"FL","zip":"00012"}]}

I would like to be able to call the data while utilizing the nested object (List) so that I am able to call the parameters from that object. 我希望能够在利用嵌套对象(列表)的同时调用数据,以便能够从该对象调用参数。 Here is what I have so far. 这是我到目前为止所拥有的。 I have the following in my code for the public classes: 对于公共类,我的代码中包含以下内容:

public class Result
{
    public string address1 { get; set; }
    public string city { get; set; }
    public sting state { get; set; }
    public sting zip { get; set; }
       }
 public class RObject
{
    public List<object> errors { get; set; }
    public bool valid { get; set; }
    public List<Result> results { get; set; }
}

Here is my code that I use to get the data: 这是我用来获取数据的代码:

var request = WebRequest.Create("http://local4510/example/00012/json.sp ");
        WebResponse response = request.GetResponse();

        string json;

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            json = sr.ReadToEnd();
        }
        JObject jResult = JObject.Parse(json); // Parses the data

        Result me = new Result()
        {
           Me.address1 = (string)jResult["results"][" address1 "] 
    Me city = (string)jResult["results"][" city "] 
Me state  = (string)jResult["results"][" state "] 
           Me zip = (string)jResult["results"]["zip"]
        };

//Console.Write(jResult); working
   Console.Write(me.address1+ ”--” + me.city+”--” + me.state+”--”+ me.zip)
Console.Read();

Aside from a few syntax errors, your main problem is you are not treating "results"" as an array of results. The code should look more like this... 除了一些语法错误外,您的主要问题是您没有将“结果”作为结果数组对待。代码看起来应该更像这样……

        Result me = new Result()
        {
           address1 = (string)jResult["results"][0]["address1"], 
           city = (string)jResult["results"][0]["city"] ,
           state  = (string)jResult["results"][0]["state"] ,
           zip = (string)jResult["results"][0]["zip"]
        };

... Notice the hard-coded [0] offset to access the first result in the array of results. ...注意,硬编码的[0]偏移量用于访问结果数组中的第一个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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