简体   繁体   中英

JSON.NET Deserialize Nested data from URL

I am trying to get JSON data via my localhost into command line. When I navigate the page via my web browser the following JSON is retuned: (I am using 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.

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