0

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();
J. Ballard
  • 33
  • 2
  • 9
  • Try using [JsonConvert.DeserializeObject](http://james.newtonking.com/json/help/index.html?topic=html/Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm). – Dustin Kingen Jul 16 '14 at 15:18
  • possible duplicate of [Deserializing JSON data to C# using JSON.NET](http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net) – Dustin Kingen Jul 16 '14 at 15:19

1 Answers1

0

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.

Les
  • 10,335
  • 4
  • 40
  • 60